Search code examples
windowspowershellvmwarepowercli

powerCLI restart VM guest from script


i'm trying to run batch script which will call ps1 in order to restart VM guest. it's working when i ran it seperate but the problem is that powerCLI on CMD load without the arguments.

i have tried run it by steps :

echo on 
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noe -c ". \"C:\Program Files (x86)\VMware\Infrastructure\PowerCLI\Scripts\Initialize-PowerCLIEnvironment.ps1\" $true"

then on cmd :

connect -viserver -server "serverName" -Protocol https -User "user"-Password "pass"

then :

Restart-VM "VMserverName"  -RunAsync -Confirm:$false

it is all works fine separately but when try to combine it all - it is not working. seems like powerCLI load faster then the console write.

i have trying

Start-Sleep -s 10

command but with no success.

how can i combine all 3 commands above in one file?


Solution

  • To execute PowerShell commands from a cmd, you will have to pass them along using the Command-Switch of from PowerShell.

    You could achieve what you want by executing the following command:

    powershell -Command "Import-Module VMware.VimAutomation.Core; Connect-VIServer -Server <server> -User <user> -Password <password>; Restart-VM <vm_name>  -RunAsync -Confirm:$false"
    

    This is a very cumbersome way of doing this. I would suggest directly using PowerShell and have at least the ability to properly format the script:

    Import-Module VMware.VimAutomation.Core
    Connect-VIServer -Server <server> -User <user> -Password <password>
    Restart-VM <vm_name>  -RunAsync -Confirm:$false
    

    You would still be able to call this PowerShell script from a cmd, by using the File-Parameter:

    powershell -File <script>