【问题标题】:Powershell Script to Create TXT Files from folders用于从文件夹创建 TXT 文件的 Powershell 脚本
【发布时间】:2019-03-10 10:36:24
【问题描述】:

我收到了一些关于如何使用此 PowerShell 脚本根据文件夹中的文件创建 txt 文件的极好的建议。

Get-ChildItem -Path "C:\Users\temp\" -Recurse -File |
Where-Object {$_.Extension -notin '.txt'} |
    ForEach-Object {
        [System.IO.File]::WriteAllText("C:\Users\temp\" + $_.BaseName + ".txt", $_.FullName)
}

如何修改此脚本以仅基于文件夹创建 txt 文件,而忽略这些文件夹中包含的文件?

谢谢!

【问题讨论】:

    标签: powershell


    【解决方案1】:

    使用更多 PowerShell 样式和 cmdlet 将是:

    $path = 'C:\Users\temp'
    Get-ChildItem -Path $path -Recurse -Directory |
        Where-Object {$_.Extension -ne '.txt'} |
        ForEach-Object {
            Add-Content -Path (Join-Path -Path $path -ChildPath ($_.BaseName + ".txt")) -Value $_.FullName
        }
    

    附言我将-notin 更改为-ne,因为这里更合适,因为您只比较单个字符串,而不是数组。

    【讨论】:

    • 再次,太棒了!彼得,你是救命稻草!
    • 说得好@Theo .. 但是很好的解决方案:)
    • 对不起,西奥。谢谢,西奥!
    【解决方案2】:

    在旧的 PowerShell 版本中,您必须执行 | Where-Object {$_.PSIsContainer -re $true}

    但现在只需将您的 -file 替换为 -directory

    【讨论】:

    • 太棒了,彼得。奇迹般有效。非常感谢。有没有办法在生成的 TXT 文档中添加文本字符串,例如“封面”?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-21
    • 2018-04-28
    • 2013-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多