Копирование Powershell через сеть p c путь - PullRequest
0 голосов
/ 02 мая 2020

У меня есть некоторый код powershell, чтобы попытаться скопировать файл изображения через сетевые устройства. Однако сценарий всегда завершается ошибкой, если целевая часть существует. Пользователь, который запускает сценарий, имеет полные разрешения для пути к файлу.

Однако Powershell не находит папку назначения каждый раз. Вот сценарий:

$Servers = (@"
    PCLIST01
    PCLIST02
    PCNAME03
    PCLIST04
    "@ -split "`r`n").Trim() 

$Source = '\\SERVER\Folder name\subfolder\100 Project Name\moneydreams.jpg'
$Destination = 'C:\ProgramData\Program Folder Name\Subfolder for Program\HTML\' -replace "C:","c$"

$Logfile = "\\SERVER\Folder name\subfolder\100 Project Name\Failed.log"
If (!(Test-Path $Logfile)) { Remove-Item $Logfile}
New-Item $Logfile -ItemType File 

ForEach ($Server in $Servers) { 
  Try {
    If (!(Test-Path "$Server\$Destination" )) {  
      ROBOCOPY "$Source" "\\$Server\$Destination" /LOG:copylog.log 
    } 
    Else { 
      Add-Content $Logfile "Folder does not exist on $Server , \\$Server\$Destination" 
    } 
  } Catch {
    Add-Content $Logfile "$Server - $($_.Exception.Message)"
    }
} 

Код не выполняется при If (! (Test-Path "$ Server \ $ Destination")). Любопытно, что если я сделаю Test-Path на $ logfile, то он также завершится неудачно, однако файл обновится с помощью нотации Add-Content! Обратите внимание, что я попытался использовать обратную галочку `для filepath, чтобы увидеть, были ли пробелы в проблеме, и это не решило проблему.

Я не понимаю, почему он не смог бы найти папка назначения и обновление!

1 Ответ

1 голос
/ 02 мая 2020

Оба Олаф и Ли верны. Вы используете Test-Path прямо противоположным образом, отрицая возвращенное логическое значение с помощью !, И вы неверно определяете конечный путь назначения.

Наконец, потому что вы не добавляете -ErrorAction Stop, ошибки это может произойти, может не оказаться в вашем catch блоке.

Попробуйте:

$Servers     = 'PCLIST01','PCLIST02','PCNAME03','PCLIST04'
$Source      = '\\SERVER\Folder name\subfolder\100 Project Name\moneydreams.jpg'
# $Destination is a template path. The server name is inserted inside the foreach loop later
$Destination = '\\{0}\c$\ProgramData\Program Folder Name\Subfolder for Program\HTML'
$Logfile     = '\\SERVER\Folder name\subfolder\100 Project Name\Failed.log'
$copyLog     = '\\SERVER\Folder name\subfolder\100 Project Name\Copylog.log'

# if the log file already exists, remove it
If (Test-Path -Path $Logfile -PathType Leaf) { Remove-Item -Path $Logfile -Force}

foreach ($Server in $Servers) { 
    # test if the server is not off-line
    # in this case i DO want to negate the result.
    if (!(Test-Connection -ComputerName $Server -Count 1 -Quiet)) {
        Add-Content -Path $Logfile -Value "Server $Server is unreachable"
        # skip this server and move on to the next one
        continue
    }
    # insert the server name to the destination
    $targetPath = $Destination -f $Server
    # $targetPath will be '\\servername\c$\ProgramData\Program Folder Name\Subfolder for Program\HTML'
    Try {
        # see if you can reach the targetpath on this server
        # -ErrorAction Stop ensures the catch block is entered on errors
        if (Test-Path -Path $targetPath -PathType Container -ErrorAction Stop) {  
            ROBOCOPY $Source $targetPath /LOG:$copyLog 
        } 
       else { 
            Add-Content -Path $Logfile -Value "Folder does not exist on $Server , $targetPath" 
        } 
    } 
    catch {
        Add-Content -Path $Logfile -Value "$Server - $($_.Exception.Message)"
    }
} 

Надеюсь, это поможет

Как видите, я ' m также НАЗВАНИЕ параметров в различных командлетах, чтобы облегчить понимание кода, а также не слепо полагаться на положение параметра, где ошибки могут быть легко допущены.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...