【问题标题】:How do I get Powershell to read the contents of a file? [closed]如何让 Powershell 读取文件的内容? [关闭]
【发布时间】:2012-12-26 08:17:40
【问题描述】:

我正在调整这个脚本来计算文件中单个单词的实例。

$txtPath = "c:\users\xxxxxx\desktop\tx"
$srcfiles = Get-ChildItem $txtPath -filter "*.txt*"
#
function wordCount ($docs) {
    Write-Host "Processing Word Count: " $docs
$s = "I saw the cat. The cat was black."
",",".","!","?",">","<","&","*","=","`n","_" |% {$s = $s.replace($_,' ')}     # Remove Chars
$w = $s.Split() |? {$_.Length -gt 0 }                                     # Array of words, spaces removed
$w | select -Unique                                                       # Unique words
$w | group                                                                # Tally
$W | group | sort name | ft name,count -AutoSize              # Sort and format
#>
}
#
ForEach ($doc in $srcfiles) { 
    Write-Host "Calling: " $doc.FullName         
    wordCount -docs  $doc.FullName    
}

目前,表示要计数的字符串的输入变量$s 是硬编码的。我想在我的$srcFiles 路径中获取每个文档并对每个文档进行计数。但是,$s = $docs 计算标题中的单词,而不是文档内容。我该怎么做?

另外,$W | group | sort name | ft name,count -AutoSize 返回以下错误:

out-lineoutput : The object of type "Microsoft.PowerShell.Commands.Internal.Format.FormatStartData" is not valid or not
 in the correct sequence. This is likely caused by a user-specified "format-table" command which is conflicting with th
e default formatting.
    + CategoryInfo          : InvalidData: (:) [out-lineoutput], InvalidOperationException
    + FullyQualifiedErrorId : ConsoleLineOutputOutOfSequencePacket,Microsoft.PowerShell.Commands.OutLineOutputCommand

我应该在哪里查找格式问题?我无法在 TechNet 上发现任何类型的默认格式信息;并且该代码最初来自的site 没有提及它们是如何工作的,也没有提及它们覆盖了哪些默认格式。我怀疑我可能需要以不同的方式传递它,但我需要更好地了解确切的错误,以便知道从哪里开始寻找。

【问题讨论】:

    标签: powershell file-read


    【解决方案1】:

    您需要使用Get-Content 来读取文件的内容。您需要组合 Get-Content 返回的行以正确计算字符数。请参阅此post

    【讨论】:

    • 或者在 V3 中,使用 Get-Content -Raw 获取包含所有文件内容的单个字符串。在 v1/v2 上,我会使用 [IO.File]::ReadAllText()。 :-)
    • 不知道那个参数。太棒了!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-30
    • 1970-01-01
    • 1970-01-01
    • 2021-02-20
    • 2012-10-08
    • 1970-01-01
    相关资源
    最近更新 更多