1

我有一些非常简单的代码,旨在将目录中的每个文件转换为 HTML。我的问题是,虽然为每个文件成功创建了一个作业,但脚本块永远不会运行。

$convert = {

Param(
    [parameter(ValueFromPipeline=$true)]
    $file
)

$content = Get-Content -Path $file.FullName
$outDir= New-Item -Type dir -Path $file.FullName + "\HTMLFiles"
$outFile = $outDir + $file.Name +  ".html"

foreach($line in $content) {
     #move the content into a variable and add some html tags
     $html = $html + '<tr>' + $line + '</tr>' +'<br>'
}
#convert the variable to .html and save the result as a file
ConvertTo-Html -Head $style -Body $html | Out-File -FilePath $outFile -Encoding "ASCII"
#empty the variable
$html = " "
}

Function main
{
Param(
   [parameter(Position=0, Mandatory=$true, ValueFromPipeLine=$true)]
   $target = $args[0]
)
#stores some html styling code
$path = $pwd.Path + "\style.txt"
$style = Get-Content -Path $path
#collect all files in the dirctory
$files = Get-ChildItem -Path $target -Recurse

foreach($file in $files) {
#for each file in the collection start a job which runs the given scriptblock (scriptblock is not working)
Start-Job -Name $file.name -ScriptBlock $convert -ArgumentList $file
}
#clean-up
Write-Host "Finished jobs"
Wait-Job *
Remove-Job -State Completed
}

main($args[0])

我对powershell相当陌生,并且已经尝试过解决这个问题的方法,但似乎无法弄清楚。

4

1 回答 1

-1
  • 更改:我从脚本块和函数中删除了参数。
  • 为什么:因为参数是由 Start-Job 传入的,并且函数也是通过 syntax 传入的function name (argument1, argument2) {}

我还从函数调用中去掉了括号,因为在 Powershell 中你调用的函数如下: function "argument1" "argument2"


$convert = {    
    $content = Get-Content -Path $file.FullName
    $outDir= New-Item -Type dir -Path $file.FullName + "\HTMLFiles"
    $outFile = $outDir + $file.Name +  ".html"

    foreach($line in $content) {
        #move the content into a variable and add some html tags
        $html = $html + '<tr>' + $line + '</tr>' +'<br>'
    }
    #convert the variable to .html and save the result as a file
    ConvertTo-Html -Head $style -Body $html | Out-File -FilePath $outFile -Encoding "ASCII"
    #empty the variable
    $html = " "
}

Function main ($args)
{
    $target = $args
    #stores some html styling code
    $path = $pwd.Path + "\style.txt"
    $style = Get-Content -Path $path
    #collect all files in the dirctory
    $files = Get-ChildItem -Path $target -Recurse

    foreach($file in $files) {
        #for each file in the collection start a job which runs the given scriptblock (scriptblock is not working)
        Start-Job -Name $file.name -ScriptBlock $convert -ArgumentList $file
    }
    #clean-up
    Write-Output "Finished jobs"
    Wait-Job *
    Remove-Job -State Completed
}

main $args[0]
于 2014-03-24T09:24:36.227 回答