【问题标题】:Checking a list to see if file exist in powershell?检查列表以查看文件是否存在于powershell中?
【发布时间】:2017-11-11 19:02:17
【问题描述】:

我有一个文件列表,我想在 powershell 中检查目录以查看它们是否存在。我对powershell不太熟悉,但这是我目前所拥有的不起作用的东西。

$filePath = "C:\Desktop\test\"
$currentDate = Get-Date -format yyyyMMdd

$listOfFiles = 
"{0}{1}testFile.txt",
"{0}{1}Base.txt",
"{0}{1}ErrorFile.txt",
"{0}{1}UploadError.txt"`
-f $filePath, $currentDate

foreach ( $item in $listOfFiles ) 
{ 
    [System.IO.File]::Exists($item)
}

这可能吗?

【问题讨论】:

    标签: powershell batch-file powershell-4.0


    【解决方案1】:

    您可以使用Test-Path cmdlet。

    $filePath = "C:\Desktop\test\"
    $currentDate = Get-Date -format yyyyMMdd
    #I'm using 1..4 to create an array to loop over rather than manually creating each entry
    #Also used String Interpolation rather than -f to inject the values
    1..4 | ForEach-Object {Test-Path  "${filePath}${currentDate}file$_.txt"}
    

    编辑: 对于更新的文件名,您可以将它们放在一个数组中以进行循环。

    "testFile","Base","ErrorFile","UploadError" | ForEach-Object {
        Test-Path  "${filePath}${currentDate}$_.txt"
    }
    

    【讨论】:

    • 感谢这确实有效,尽管我并不是真的要这样命名我的文件。我现在对其进行了更改,以显示我真正要检查的内容。
    • 谢谢@BenH。我似乎无法投票,但确实接受了。
    【解决方案2】:

    是的,您可以在 PowerShell 中执行此操作。

    $filePath = "C:\Desktop\test\$((Get-Date).ToString("yyyyMMdd"))"
    
    foreach ( $n in 1..4 ) {
        Test-Path $($filePath +"file$n.txt")
    }
    

    【讨论】:

    • 循环中的所有$items 都将返回$TrueTest-Path,因为Get-ChildItem 只会获取存在的文件。
    • @Benh 好点,试图走捷径的愚蠢逻辑错误。
    猜你喜欢
    • 2015-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-31
    • 2015-04-10
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    相关资源
    最近更新 更多