Question

I am trying to create a PowerShell script by another PowerShell script. I have something like: >

    $scriptBlock = {
    write-host "this is the body of the script that I want to add to another PS script"
    if($true){
     write-host "so that I can execute this automatically created script somewhere "
        }
    }
    $scriptBlock | Out-String -Width 4096 | Out-File "c:\test.ps1"

AtRunUnattended.exe "$($Dict.Get_Item("MASTER_DIRECTORY_PATH"))\MEDIA_FILE\" /S /noreboot /L logfile="%TEMP%\AT $($Dict.Get_Item("PRODUCT_NAME")) V8.4.log" altsource="C:\temp\baf\mediafile"

However, when I have some long single-line scripts like the one shown above, it gets automatically wrapped so the out-put .ps1 file would not work as if I had invoked the script directly from the parent script. So in the .ps1 file that the parent .ps1 script created, the code then looks like this:

ElseIf($str.StartsWith("DRIVER_DATE=")){$str = "DRIVER_DATE=$(Get-Date 
-f MM-dd-yyyy))"}

which will not run properly if it is run.

So does anybody know how to text-format scriptblocks so that they can be properly written to another child script file for further execution? I did some research and I think that it might have something to do with PS's internal text buffer width or something. I tried other out-file methods as well like [System.IO.StreamWriter], however all of them look the same--wrapped and limited to a certain width per line.

Please help me, thank you!

The entire purpose of this thing is to generate some scripts automatically and remotely execute these created scripts on other machines.

Was it helpful?

Solution

Use the -Width parameter with the Out-File cmdlet as follows:

Out-File -FilePath "c:\test.ps1"  -Width 4096

OTHER TIPS

the variable will not be expanded in single quote. May be you need a sample like this:

$scripts=@'
$date=get-date
"Hello,now is $date"
'@

$scripts | Out-File second.ps1
./second.ps1 

Output is:

Hello,now is 09/23/2013 23:41:18
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top