【问题标题】:Check if a file/folder exists in remote system using powershell使用 powershell 检查远程系统中是否存在文件/文件夹
【发布时间】:2021-09-20 19:45:04
【问题描述】:

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

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

我知道如何做到这一点的逻辑。但是,由于某种原因,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

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

但我需要从本地系统检查文件是否存在于远程机器上。

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

谢谢!

【问题讨论】:

  • 为什么不用 Robocopy 处理副本?
  • 我想我们看到了这个问题,你能告诉我们来自$Files的几行是什么样的吗?

标签: powershell


【解决方案1】:

首先,您没有将 PSSession 用于任何事情。它们看起来是多余的。

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

 $existsOnRemote = Invoke-Command -Session $s {param($fullpath) Test-Path $fullPath } -argumentList $item.Fullname; 
 if(-not $existsOnRemote){
    Copy-Item -Path $item.FullName -ToSession $s -Destination $item.Fullname;
 }  

【讨论】:

  • 完成 :) @CmdrTchort
  • 只是为了添加,argumentList 是位置的而不是命名的。容易被忽视。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-16
  • 1970-01-01
  • 1970-01-01
  • 2011-05-07
  • 2012-02-05
相关资源
最近更新 更多