【问题标题】:I am trying to create a new file and add contents to the new file based on input parameters send我正在尝试创建一个新文件并根据输入参数将内容添加到新文件发送
【发布时间】:2017-06-24 15:32:43
【问题描述】:

我正在尝试创建 powershell 脚本,该脚本将根据输入参数(计数器、文件名)创建新文件并在其中添加内容。
对于以 Ab 开头的每个标题行,将创建一个新文件,并将从输入文件添加该行。
一旦该行已经写入,下次将不会在新文件中再次写入。结束行以 Br 开头,但是在调试时出现错误

[DBG]>>> 停止于:$_.PSParentPath.Replace("Microsoft.PowerShell.Core\FileSystem::", "")

代码示例

$fileinput = Get-Content c:\abc.txt
$fileinput1 = Get-Content c:\abc1.txt

foreach($line in $fileinput)
 {
    $array = $line.split(',')
    test-param $array[0] $array[1]
}

function test-param {
param ([int]$input1, [String]$input2)
$chunk = 0
foreach($line in $fileinput1) {
    if ($line.substring(0,2) -eq 'Ab')
    {
        $chunk++;
        New-Item -Itemtype 'File' -Path "d:\$input2"   
    }
    if ($chunk -eq $input1 -And $line.substring(0,2) -eq 'Br')
    {
        Add-Content -Path "d:\$input2" -Value $line
        break
    }
    Add-Content -Path "c:\$input2" -Value $line
}
}

【问题讨论】:

  • IIRC New-Item 需要 -Name-Value 参数
  • 根据help New-Item -Full-Name是必填参数,但是示例3和示例4没有使用。

标签: powershell


【解决方案1】:

我建议强制 $input2 输入“字符串” - 如果它不是字符串,它将无法使用该变量来构造路径。

确实需要查看两个输入文件的一些示例内容才能进一步评论。

纯粹从优化的角度来看,我会将 $fileinput1 的内容加载到 test-param 函数之外的数组中。每次调用 test-param 函数时,都会再次加载整个文件,速度较慢,并且会增加内存使用量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-04-04
    • 1970-01-01
    • 2021-07-15
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多