使用powershell检查远程系统中是否存在文件/文件夹

时间:2017-10-04 13:08:17

标签: powershell ps1

我已经搜索过这个并找到了很多答案。但是,它们似乎都不起作用。

我正在编写一个脚本,用于将一些文件从本地计算机复制到远程服务器。在复制文件之前,我需要检查文件/文件夹是否已存在。如果该文件夹不存在,则创建一个新文件夹,然后复制这些文件。如果文件已存在于指定位置,则只需覆盖该文件。

我得到了如何做到这一点的逻辑。但是,由于某些原因,Test-Path似乎不起作用。

$server = #list of servers
$username = #username
$password = #password
$files = #list of files path to be copied
foreach($server in $servers) {
    $pw   = ConvertTo-SecureString $password -AsPlainText -Force
    $cred = New-Object Management.Automation.PSCredential ($username, $pw)
    $s = New-PSSession -computerName $server -credential $cred
    foreach($item in $files){
        $regex = $item | Select-String -Pattern '(^.*)\\(.*)$'
        $destinationPath = $regex.matches.groups[1]
        $filename = $regex.matches.groups[2]        
        #check if the file exists on local system
        if(Test-Path $item){
            #check if the path/file already exists on remote machine
            #First convert the path to UNC format before checking it
            $regex = $item | Select-String -Pattern '(^.*)\\(.*)$'
            $filename = $regex.matches.groups[2]
            $fullPath = $regex.matches.groups[1]
            $fullPath = $fullPath -replace '(.):', '$1$'
            $unc = '\\' + $server + '\' + $fullPath
            Write-Host $unc
            Test-Path  $unc #This always returns false even if file/path exists
            if(#path exists){
                Write-Host "Copying $filename to server $server"
                Copy-Item -ToSession $s -Path $item -Destination $destinationPath
            }
            else{
                #create the directory and then copy the files
            }
        }
        else{
            Write-Host "$filename does not exists at the local machine. Skipping this file"
        }           
    }
    Remove-PSSession -Session $s
}

检查远程计算机上是否存在文件/路径的条件始终失败。不知道为什么。

我在powershell上手动尝试了以下命令,该命令在远程计算机上返回true,在本地计算机上返回false。

在本地计算机上:

Test-Path '\\10.207.xxx.XXX\C$\TEST'
False

在远程计算机上:

Test-Path '\\10.207.xxx.xxx\C$\TEST'
True
Test-Path '\\localhost\C$\TEST'
True

因此,即使我手动或通过脚本尝试,很明显命令也会失败。但是当我尝试从远程系统或服务器执行此操作时,命令会通过。

但我需要检查本地系统远程计算机上是否存在该文件。

我错过了什么吗?有人可以帮我理解这里发生了什么吗?

谢谢!

1 个答案:

答案 0 :(得分:2)

首先,您没有使用PSSessions进行任何操作。他们看起来多余。

如果您的本地路径与目的地相同,并且您正在使用WMF / Powershell 4或更新版本;我建议您停止使用正则表达式和UNC路径并执行以下操作,这将简化并删除大部分代码:

#include <opencv2/opencv.hpp>

std::string mTitle = "title of my window";

while (cvGetWindowHandle(mTitle.c_str()))
{
   // ...
}
相关问题