thinker123 thinker123 - 3 months ago 13
PowerShell Question

How do I make a block of script write to another script?

I am trying to write a script that writes PowerShell profiles. This is helpful for new users who want a profile that will automate what they are doing daily.

I am trying to figure out how I can take a large chunk of script with various objects and write it to a profile that was just made a few lines before.

The problem I am running into is that I am trying to turn a large block of script into a string that can then be written to that profile.

An example:

$text='"welcome, want to go to site?"

$goyn=read-host -prompt "enter y or n"

if($goyn -eq 'y'){
start 'www.google.ca'
}
else{"continue on your journey of awesomeness"}


Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
Get-WmiObject -Class Win32_OperatingSystem -ComputerName localhost |
Select-Object -Property CSName,@{n="Last Booted";
e={[Management.ManagementDateTimeConverter]::ToDateTime($_.LastBootUpTime)}}'


I have tried putting it between single quotes then passing it into a variable but to no avail.

Answer

It's not completely clear what you're asking but it sounds like you're having trouble with quoting. You can use here-strings as Patrick Meinecke suggested. That looks like this:

$text=@'
"welcome, want to go to site?"

$goyn=read-host -prompt "enter y or n"

if($goyn -eq 'y'){
start 'www.google.ca'
}
else{"continue on your journey of awesomeness"}


Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
Get-WmiObject -Class Win32_OperatingSystem -ComputerName localhost |
Select-Object -Property CSName,@{n="Last Booted";
e={[Management.ManagementDateTimeConverter]::ToDateTime($_.LastBootUpTime)}}
'@

Another thing you can do is just use a [ScriptBlock] naturally. This also gives you the benefit of syntax highlighting and tab completion in your editor.

$sb = {
    "welcome, want to go to site?"

    $goyn=read-host -prompt "enter y or n"

    if($goyn -eq 'y'){
    start 'www.google.ca'
    }
    else{"continue on your journey of awesomeness"}


    Set-ExecutionPolicy RemoteSigned -Scope CurrentUser
    Get-WmiObject -Class Win32_OperatingSystem -ComputerName localhost |
    Select-Object -Property CSName,@{n="Last Booted";
    e={[Management.ManagementDateTimeConverter]::ToDateTime($_.LastBootUpTime)}}
}

You can pass the script block directly to something like Set-Content:

Set-Content -Path C:\my\profile.ps1 -Value $sb

But if you want to be sure you're getting a string (maybe not all cmdlets are as forgiving), just call .ToString() on the script block:

$text = $sb.ToString()