Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issues finding and replacing strings in PowerShell


I'm rather new to PowerShell and I'm trying to write a PowerShell script to convert some statements in VBScript to Microsoft JScript. Here is my code:

$vbs = 'C:\infile.vbs'
$js = 'C:\outfile.js'

(Get-Content $vbs | Set-Content $js)
(Get-Content $js) |
 Foreach-Object { $_ -match "Sub " } | Foreach-Object { "$_()`n`{" } | Foreach-Object { $_ -replace "Sub", "function" } | Out-File $js
 Foreach-Object { $_ -match "End Sub" } | Foreach-Object { $_ -replace "End Sub", "`}" } | Out-File $js
 Foreach-Object { $_ -match "Function " } | Foreach-Object { "$_()`n`{" } | Foreach-Object { $_ -replace "Function", "function" } | Out-File $js
 Foreach-Object { $_ -match "End Function" } | Foreach-Object { $_ -replace "End Function", "`}" } | Out-File $js

What I want is for my PowerShell program to take the code from the VBScript input file infile.vbs, convert it, and output it to the JScript output file outfile.js. Here is an example of what I want it to do:

Input file:

Sub HelloWorld
 (Code Here)
End Sub

Output File:

function HelloWorld()
{
 (Code Here)
}

Something similar would happen with regard to functions. From there, I would tweak the code manually to convert it. When I run my program in PowerShell v5.1, it does not show any errors. However, when I open outfile.js, I see only one line:

False

So really, I have two questions.
1. Why is this happening?
2. How can I fix this program so that it behaves how I want it to (as detailed above)?

Thanks,
Gabe

like image 445
GMills Avatar asked Dec 28 '25 22:12

GMills


1 Answers

You could also do this with the switch statement. Like so:

$vbs = 'C:\infile.vbs'
$js = 'C:\outfile.js'

Get-Content $vbs | ForEach-Object {
        switch -Regex ($_) {
        'Sub '{
            'function {0}(){1}{2}' -f $_.Remove($_.IndexOf('Sub '),4).Trim(),[Environment]::NewLine,'{'
        }
        'End Sub'{
            '}'
        }
        'Function ' {
            'function {0}(){1}{2}' -f $_.Remove($_.IndexOf('Function '),9).Trim(),[Environment]::NewLine,'{'
        }
        'End Function' {
            '}'
        }
        default {
            $_
        }
    }
} | Out-File $js
like image 98
Kirill Pashkov Avatar answered Dec 30 '25 12:12

Kirill Pashkov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!