【问题标题】:If statement - how to check if a path contains a fileIf 语句 - 如何检查路径是否包含文件
【发布时间】:2017-10-02 12:19:39
【问题描述】:

我刚开始玩 powershell,所以请执行我的新手错误。 我正在搜索文件并将文件的路径存储在变量中,然后我想检查该路径中是否有特定文件,然后 删除他们。我在这方面找不到太多帮助,我认为 if 语句中存在问题,但我无法弄清楚。

代码如下:

$startDirectory = ".\somepath\"
$FindFileXml = Get-Childitem $startDirectory 

$StorePaths = Get-Childitem $FindFileXml -include "file.xml" -recurse 
if($StorePaths -eq "somefile.cs" -and "diffrentfile.cs")
{
    Remove-Item "somefile.cs"
    Remove-Item "diffrentfile.cs"
}
else{
Write-host "file not found!"
}

更新:

$StorePaths = Get-Childitem $FindFilterXml-Filter "file.xml" -recurse

$StorePaths | Select-Object -ExpandProperty Directory 
| Get-ChildItem | 

Where-Object {($_.Name -eq 'GeneratedCode.cs') -or ($_.Name -eq 'TypedEnums.cs')} 

| Remove-Item

这会将 File.xml 的路径存储在 $StorePaths 中吗?如果是这样,我该如何复制它,例如 Copy-Item $StorePath.name .\somepath?

【问题讨论】:

  • 是的,这会将file.xml的路径存储在$storePaths中。您可以通过管道将其复制到 copy-item cmdlet,例如。 G。 :$StorePaths | Copy-Item -Destination 'your_path'

标签: shell powershell powershell-3.0


【解决方案1】:

不需要这里需要一个 if 语句。只需过滤您要删除的文件的结果并将它们管道Remove-Item cmdlet:

$StorePaths | 
    Where-Object {($_.Name -eq 'somefile.cs') -or ($_.Name -eq 'diffrentfile.cs')} |
    Remove-Item

更新: 此示例仅删除存在 file.xml 的目录中的文件:

Get-Childitem $FindFileXml -Filter "file.xml" -recurse | 
    Select-Object -ExpandProperty Directory |
    Get-ChildItem |
    Where-Object {($_.Name -eq 'somefile.cs') -or ($_.Name -eq 'diffrentfile.cs')} |
    Remove-Item

【讨论】:

  • 我试过你的代码,但文件没有被删除。 file.xml 始终位于包含 somefile.csdiffrentfile.cs 的文件夹中,这可能是什么问题?
  • 啊,刚刚看到你使用了-include参数。可以省略吗?
  • 嗯,我必须先找到 file.xml 的路径,因为文件 file.xml 的位置不同。除了使用-include 参数之外,还有其他解决方案吗?
  • 你是救生员!完美运行谢谢。
猜你喜欢
  • 2019-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-17
  • 2017-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多