VMware Cloud Community
vmSpecDaniel
Enthusiast
Enthusiast
Jump to solution

Execute script from file against a virtual machine

Hi,

I have a script (c:\script.ps1) that I want to execute against a virtual machine. Can anyone tell me how to do it?

When I want to run single command on vm I do this:

>> $cred = Get-Credential

>> Invoke-VMScript -VM win1 -GuestCredential $cred -ScriptText "dir"

but I don't know how to put script to a variable so that I can place it after -ScriptText parameter.

P.S. Script is not on virtual machine it's on the computer that I have PowerCLI installed.

0 Kudos
1 Solution

Accepted Solutions
vmSpecDaniel
Enthusiast
Enthusiast
Jump to solution

LucD thanks for help

I managed to do it this way:

$script = Get-Content -Path C:\script.ps1 | Out-String

Invoke-VMScript -VM win1 -GuestCredential $cred -ScriptText $script


without Out-String I got "Cannot convert System.Object[] to the type System.String" error.

View solution in original post

0 Kudos
4 Replies
LucD
Leadership
Leadership
Jump to solution

I mostly use a here-string for that, something like

$myscript = @"

dir

date

time

"@

Invoke-VMScript -VM win1 -GuestCredential $cred -ScriptText $myscript


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

0 Kudos
vmSpecDaniel
Enthusiast
Enthusiast
Jump to solution

Yes I know this way but what about a 300-line script? Pasting it inside the window is not the best way. I want the variable to reed what's inside the script file.

0 Kudos
LucD
Leadership
Leadership
Jump to solution

Then you could use the Get-Content cmdlet to read the script file into a variable.


Blog: lucd.info  Twitter: @LucD22  Co-author PowerCLI Reference

vmSpecDaniel
Enthusiast
Enthusiast
Jump to solution

LucD thanks for help

I managed to do it this way:

$script = Get-Content -Path C:\script.ps1 | Out-String

Invoke-VMScript -VM win1 -GuestCredential $cred -ScriptText $script


without Out-String I got "Cannot convert System.Object[] to the type System.String" error.

0 Kudos