Check if a file exists or not in Windows PowerShell?

后端 未结 7 1542
自闭症患者
自闭症患者 2020-12-03 02:38

I have this script which compares files in two areas of the disk and copies the latest file over the one with the older modified date.

$filestowatch=get-con         


        
相关标签:
7条回答
  • 2020-12-03 02:44

    You want to use Test-Path:

    Test-Path <path to file> -PathType Leaf
    
    0 讨论(0)
  • 2020-12-03 02:45

    Test-Path may give odd answer. E.g. "Test-Path c:\temp\ -PathType leaf" gives false, but "Test-Path c:\temp* -PathType leaf" gives true. Sad :(

    0 讨论(0)
  • 2020-12-03 02:47
    cls
    
    $exactadminfile = "C:\temp\files\admin" #First folder to check the file
    
    $userfile = "C:\temp\files\user" #Second folder to check the file
    
    $filenames=Get-Content "C:\temp\files\files-to-watch.txt" #Reading the names of the files to test the existance in one of the above locations
    
    foreach ($filename in $filenames) {
      if (!(Test-Path $exactadminfile\$filename) -and !(Test-Path $userfile\$filename)) { #if the file is not there in either of the folder
        Write-Warning "$filename absent from both locations"
      } else {
        Write-Host " $filename  File is there in one or both Locations" #if file exists there at both locations or at least in one location
      }
    }
    
    0 讨论(0)
  • 2020-12-03 02:55

    The standard way to see if a file exists is with the Test-Path cmdlet.

    Test-Path -path $filename
    
    0 讨论(0)
  • 2020-12-03 02:56

    Just to offer the alternative to the Test-Path cmdlet (since nobody mentioned it):

    [System.IO.File]::Exists($path)
    

    Does (almost) the same thing as

    Test-Path $path -PathType Leaf
    

    except no support for wildcard characters

    0 讨论(0)
  • 2020-12-03 02:57

    Use Test-Path:

    if (!(Test-Path $exactadminfile) -and !(Test-Path $userfile)) {
      Write-Warning "$userFile absent from both locations"
    }
    

    Placing the above code in your ForEach loop should do what you want

    0 讨论(0)
提交回复
热议问题