Call CSV Data and Startup VM's depending on State - powershell

I am very new to Powershell and I am wanting to write a script that will check the status of Virtual Machines i.e running or stopped, then when the host machine reboots depending on the status of the VM's pior the the reboot it will start them or keep them in a stopped state.
So far I have written a script that will auto start all the local VM's on the host machine on start-up, however sometimes we shutdown a VM for a reason and don't want it starting back up again.
I have started writing a script that captures all the VM's on a host and writes it to a CSV file:
Get-VM | select VMName, State, Uptime| Export-CSV D:\VM.csv -NoTypeInformation
This produces the VMName and the current state ie "Running" or "Off"
My plan is to have this script run via a task scheduler every 12hrs and on-start up have a ps1 script run and grab the VMName and State and depending on the data Start the VM if it was previosuly running, or keep it in a stopped state if the value was set to "off"
Is there an easy way to write this?
Thanks.

Maybe the following article is helpful to you:
Using Task Scheduler for PowerShell
You can find the documentation of VM PowerShell CMDLET at VM PowerShell cmdlet
So for example if you have CSV file (vmstatus.csv) with VM Name and VM Status like:
VMNAME,VMstatus,
vm1,1
vm2,0
vm3,1
then maybe you can restart VM where the status is zero
$statusresult = Import-Csv -path C:\temp\vmstatus.csv
foreach ($st in $statusresult){
if ($St.VMSTATUS -eq 0){
Start-VM -Name $st.VMNAME
}
}

Related

Why process that terminated by script from PowerCli stuck in "suspended" mode

When I run a script trough PowerCLI after connecting to a VM, I get a strange behavior of some processes, I'm using the "Invoke-VMScript" command that is running an EXE file (compiled in .Net 4.5) that looks for running process and try to kill them.
For some reason some process doesn't get closed, and stuck in "Suspended" mode. When they stuck in this mode even if I tried to remove them from the task manager I get an error "The operation could not be complete, Access is denies."
I'm logged in with the Administrator user
The powershell script that I'm using is:
$executeCommand = "call D:\myCleaningProcess.exe $param1";
Invoke-VMScript -VM $vmName -GuestUser $vmUser -GuestPassword $vmPass -ScriptText $executeCommand
*When running manually the file "EXE" it's works as expected and the process get killed.
Anyone know why I get this strange behavior?
You need to use the -ScriptType Bat parameter when calling EXEs in this manner. See example 3 for reference: https://pubs.vmware.com/vsphere-55/index.jsp?topic=%2Fcom.vmware.powercli.cmdletref.doc%2FInvoke-VMScript.html

Check whether a RunspacePool is already open on a machine

I have a process that runs Powersell script on a VM. This script defines a RunspacePool on the VM and sets threshold (no. of Runspaces) based on the resource capability of that VM. This process is recurring so I do not want it to keep defining and opening RunspacePools when there is already one defined and opened on that VM
At the beginning of the Powershell script, I have tried to check whether a Runspacepool is already defined\ opened by calling RunspacePoolStateInfo or RunspacePoolAvailability properties. But these are not identified as the Runspacepool object itself is not available in the new window that the process opens up to run the script
I am basically looking for a way to identify that a RunspacePool is open on a VM by using Powershell scripting
Answer for PowerShell V5 and newer
You can get the Runspacess in the current processes by running
Get-Runspace
or if you know the name
Get-Runspace -Name <name>
Remote Runspaces in PowerShell V5
If the Runspace you want to check is in another process, you must first do this.
Enter-PSHostProcess -Id <int>
or
Enter-PSHostProcess -Process <ProcessObject>

Check connectivity on virtual machine in vCenter

I am trying to write a small powershell script that checks the health of a newly started server. Here's what I want to do:
Start VM if it's not already started
Wait for Guest Tools to start running
Run the powershell script Test-Connection MyDCServer -Quiet using Invoke-VMScript
Act on whether the check return $true or not.
I have 1. and 2. donem but I am running into trouble on 3. All I get back from Invoke-VMScript is a string presenting the output from the script, when I really want the return value from the script that I invoked.
Is this possible?
I found the solution:
$result = Invoke-VMScript ...
$result.ScriptOutput
$result.ExitCode

Get-WmiObject returns nothing in a PowerShell Script running as scheduled task

My entire script is about 800 lines long and contains a lot of other functionality so i will focus on the actual problem in this question.
I made a PowerShell script that uses the Get-WmiObject cmdlet to get the installed Windows Updates on the computer it runs on.
The full command looks like this:
$windowsupdates = Get-WmiObject Win32_QuickFixEngineering -ErrorAction Stop |
Select-Object Caption, CSName, Description, FixComments, HotFixID, InstallDate, InstalledBy, InstalledOn, Name, ServicePackInEffect, Status -ErrorAction Stop |
Sort-Object -Property InstallDate -ErrorAction Stop
After this command i iterate through the found updates via ForEach and generate a csv file from them.
This works entirely fine when running the script manually but as soon as i run it as scheduled task under the exact same user i used to run it manually it will no longer find any updates installed on the system.
There are no exceptions thrown and everything seems as if the script was running normal.
When i finish the script a scheduled task will be used to run it because it has to run in a specific time interval so i have to make sure it runs fine as scheduled task. The script will be running under a standard user without administrator permissions (i will not be able to run it under an administrator user so don't suggest me doing that, it DOES work on an administrator user though) so i'm sure it is a security/access problem because the script runs fine under an administrator user as scheduled task.
The only other question i found about this issue is WMI query in powershell script returns no object when run in a scheduled task and i DID check the "Run with highest privileges" Checkbox but it still doesn't work. Has anybody ever experienced this issue and knows a solution?

How can I run a PowerShell script after reboot?

I have a powershell script that tails specifics logs. If there is no update to the logs within a specific time span, an alert is then sent to nagios (as this depicts that the service is no longer running).
The powershell script works great when run manually, but my issue is that I want it to load up on reboot. I've tried creating a scheduled task that repeats itself every 5 minutes using the arguments '-noexit -file C::\script.ps1'. The problem is then that my script doesn't actually work when run as a scheduled task.
The execution policy is set to Unrestricted, so the script runs, but the code doesn't execute and work like it does when manually run.
FWIW, the code is:
function Write-EventlogCustom($msg) {
Write-EventLog System -source System -eventid 12345 -message $msg
}
Get-Content -Path C:\test.log -Wait | % {Write-EventlogCustom $_}
So if I update test.log while the powershell script runs a scheduled task, the event log doesn't get updated. However, when I run this script manually, and update to test.log, it does appear in the event viewer.
I'm hoping that a second set of eyes might find something that I may have missed?
As #Tim Ferrill has mentioned, I needed to run the process with task schedulers 'Run with highest privileges' setting. This resolved the issue.