Hyper-V Script Won't Recognize Remote Virtual Machines - powershell

I am creating a PowerShell script to be run as a scheduled task. It's purpose is to create a snapshot on each of our virtual machines every Monday. I've created a short script for each VM. After establishing a remote session to our local Hyper-V server, it should simply find our virtual machine and create a Snapshot. This is what it looks like when testing:
PS C:\Users\crhoden\Documents\Scripts\HyperV Snapshot Job> .\win7
Name State CPUUsage(%) MemoryAssigned(M) Uptime Status Version
---- ----- ----------- ----------------- ------ ------ -------
Windows 10 Professional Off 0 0 00:00:00 Operating normally 7.0
Windows 7 Professional Pre-Alpha Saved 0 0 00:00:00 Operating normally 7.0
Windows 8.1 Professional Pre-Alpha Off 0 0 00:00:00 Operating normally 7.0
Windows Server 2012 R2 Off 0 0 00:00:00 Operating normally 7.0
Get-VMSnapshot : Hyper-V was unable to find a virtual machine with name "Windows 7 Pro".
At C:\Users\crhoden\Documents\Scripts\HyperV Snapshot Job\Win7.ps1:6 char:1
+ Get-VMSnapshot -VMName $vmname | Where-Object {$_.CreationTime -lt (G ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [Get-VMSnapshot], VirtualizationException
+ FullyQualifiedErrorId : ObjectNotFound,Microsoft.HyperV.PowerShell.Commands.GetVMSnapshot
Checkpoint-VM : Hyper-V was unable to find a virtual machine with name "Windows 7 Pro".
At C:\Users\crhoden\Documents\Scripts\HyperV Snapshot Job\Win7.ps1:7 char:1
+ Checkpoint-VM -Name $vmname -SnapshotName "Weekly Snapshot $((Get-Dat ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [Checkpoint-VM], VirtualizationException
+ FullyQualifiedErrorId : ObjectNotFound,Microsoft.HyperV.PowerShell.Commands.CheckpointVM
[hypervserver]: PS C:\Users\crhoden\Documents> get-vm
Name State CPUUsage(%) MemoryAssigned(M) Uptime Status
---- ----- ----------- ----------------- ------ ------
Windows 10 Pro Running 1 1172 1.00:49:27 Operating normally
Windows 7 Pro Running 0 1024 10:54:07 Operating normally
Windows 8 Pro Running 0 1159 16.22:02:43 Operating normally
Windows 8.1 Pro Running 1 1716 16.21:43:03 Operating normally
[hypervserver]: PS C:\Users\crhoden\Documents>
As you can probably tell, when I manually run a "get-vm", the remote machines turn up just fine. But when ran as a script, it still searches my workstation instead. Here are the contents of the script:
Enter-pssession -computername hypervserver
start-sleep -s 10
cd C:\
$vmname = 'Windows 7 Pro'
get-vm
Get-VMSnapshot -VMName $vmname | Where-Object {$_.CreationTime -lt (Get-Date).AddDays(-15) } | Remove-VMSnapshot
Checkpoint-VM -Name $vmname -SnapshotName "Weekly Snapshot $((Get-Date).toshortdatestring())"
I added the start-sleep command as an attempted fix, thinking commands were firing before the connection was established. No such luck. The kicker is if I run through this script line by line, it works just fine. Any help is appreciated. EDIT: It also works perfect when pasting in the contents of the script in their entirety.

Enter-PSSession is for interactive sessions only, so working interactively or pasting into a session does work, but not in a script which is by nature not interactive.
You can either
execute the script remotely or
use the -ComputerName parameter of Get-VMSnapShot
As you discovered by yourself the used cmdlet has to match the Hyper-Vserver version.

Related

remove dell optimizer service - powershell

Problem -
Unable to uninstall dell optimizer service
Long version -
i am looking to write what should be a very basic script for removing dell optimizer. when its fully installed and i run get-package I get the following.
When this is uninstalled by piping into uninstall-package. we are still left with dell optimizer service.
this is after stopping the services as well.
PS C:\WINDOWS\system32> Get-Package -Name *optimizer*
Name Version Source ProviderName
---- ------- ------ ------------
Dell Optimizer 2.0.651.0 C:\Program Files\Dell\DellOpt... msi
DellOptimizerUI 2.0.651.0 C:\Program Files (x86)\Dell\D... msi
Dell Optimizer Service 2.0.651.0 Programs
dell optimizer service in programs and features
the uninstall string as below when run does not accept -remove or -runfromtemp HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall
"C:\Program Files (x86)\InstallShield Installation Information{286A9ADE-A581-43E8-AA85-6F5D58C7DC88}\DellOptimizer.exe" -remove -runfromtemp
+ ... A9ADE-A581-43E8-AA85-6F5D58C7DC88}\DellOptimizer.exe" -remove -runfro ...
+ ~~~~~~~
Unexpected token '-remove' in expression or statement.
At line:1 char:199
+ ... -A581-43E8-AA85-6F5D58C7DC88}\DellOptimizer.exe" -remove -runfromtemp
+ ~~~~~~~~~~~~
Unexpected token '-runfromtemp' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken
the exe is located at
C:\Program Files (x86)\InstallShield Installation Information{286A9ADE-A581-43E8-AA85-6F5D58C7DC88}\DellOptimizer.exe
I have used 7zip to unpackage the .exe to see if there was an uninstall file but to no avail.
I believe it has something to do with its providername being program and also the dell optimizer service does not appear when you search for the below in ciminstance.
Im unsure how to find which CIMclass it would fall into as it could be a step in the right direction
PS C:\WINDOWS\system32> Get-CimInstance -ClassName Win32_Product | Sort-Object
Has anyone done something like this before? or anything i could try?
i worked it out. it was a silly mistake and needed to run the uninstall string in command prompt
#stop dell optimizer services
Get-Service -Name "DellOptimizer" | Stop-Service
#Get Dell Optimizer from registry
$uninstallstring = get-itemproperty 'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*' | Where-Object { $_.DisplayName -match "optimizer service"}
#get the uninstall string for dell optimizer
$uninstallstring = $removeapp.UninstallString
#add the silent parameter and run throguh cmd to uninstall
cmd /c $uninstallstring -silent
fix for your script
#stop dell optimizer services
Get-Service -Name "DellOptimizer" | Stop-Service
#Get Dell Optimizer from registry
$uninstallstring = get-itemproperty 'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*' | Where-Object { $_.DisplayName -match "optimizer service"}
#get the uninstall string for dell optimizer
$uninstallstring = $uninstallstring.UninstallString
#add the silent parameter and run throguh cmd to uninstall
cmd /c $uninstallstring -silent
why not just follow their documentation and download the exe. extract it to get the DellOptimizer.exe package it up with a simple powershell script that run DellOptimizer.exe /remove /silent

Powershell Direct from Jenkins to Hyper-v Windows 10

I have been trying to use Jenkins to automatically test VMs, which includes copying new code into the VM, or running certain commands from the host into the VM using Powershell Scripts.
However, I've been running into an error trying to using "Invoke-Command" or "New-PSSession" to a hyper-V Windows 10 VM in Jenkins Freestyle and Pipeline projects.
This is the environment Jenkins is running on:
Windows Specifications:
Edition: Windows Server 2019 Standard
Version: 1809
OS build: 17763.379
Jenkins ver. 2.190.1
Hyper-V Manager: 10.0.17763.1
This is the Powershell Scripts that I've written in a "Windows Powershell" Build Step in a freestyle project:
# Win10-Clean is currently running and the credentials are for the Win 10 VM.
$ErrorActionPreference = "Stop"
$VMName = "Win10-Clean"
$username = "username"
$pwd = "password"
$secpasswd = ConvertTo-SecureString $pwd -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ("$username", $secpasswd)
Get-VM
Invoke-Command -Credential $mycreds -VMName $VMName -ScriptBlock {host}
I expect the output to be:
Running as SYSTEM
Building on master in workspace G:\ci_server_1\jenkins\workspace\powershell-testing-ground
[powershell-testing-ground] $ powershell.exe -NonInteractive -ExecutionPolicy ByPass "& 'C:\Windows\TEMP\jenkins6936256398230803297.ps1'"
Name State CPUUsage(%) MemoryAssigned(M) Uptime Status Version
---- ----- ----------- ----------------- ------ ------ -------
Win10-Clean Running 0 1854 5.14:10:42.5100000 Operating normally 8.3
PSComputerName : Win10-Clean
RunspaceId : 56151e46-5772-458f-8f11-9beba5491bc2
Name : ServerRemoteHost
Version : 1.0.0.0
InstanceId : fe09fc40-8434-4a7c-903b-b7b2c3f88506
UI : System.Management.Automation.Internal.Host.InternalHostUserInterface
CurrentCulture : en-US
CurrentUICulture : en-US
PrivateData :
DebuggerEnabled : True
IsRunspacePushed : False
Runspace : System.Management.Automation.Runspaces.LocalRunspace
Finished: SUCCESS
But what I got was this:
Running as SYSTEM
Building on master in workspace G:\ci_server_1\jenkins\workspace\powershell-testing-ground
[powershell-testing-ground] $ powershell.exe -NonInteractive -ExecutionPolicy ByPass "& 'C:\Windows\TEMP\jenkins233354859509300046.ps1'"
An error has occurred which Windows PowerShell cannot handle. A remote session might have ended.
At C:\Windows\TEMP\jenkins233354859509300046.ps1:7 char:1
+ Invoke-Command -Credential $mycreds -VMName Build_VM -ScriptBlock {ho ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (Build_VM:String) [], PSRemotingDataStructureException
+ FullyQualifiedErrorId : PSSessionStateBroken
Build step 'Windows PowerShell' marked build as failure
Finished: FAILURE
After referring to the official microsoft web page regrding this issue, the possible causes are:
VM exists but not running
Guest OS does not support PowerShell Direct
Powershell isn;t avaliable in the guest yet:
Operation system hasn't booted yet
OS can't boot correctly
Some boot time event needs user input
A bug in current builds where credentials must be explicitly passed with -Credential. Run Restart-Service -Name vmicvmsession as a work around.
However, from the output from Jenkins, the VM that I've been trying to connect to is "Running" and it is booted up properly.
Then, I've tried to "Invoke-Command" and "New-PSSession" into the VM from the host directly and I am able to connect to the VM.
I've also tried the same thing in a Jenkins installed in a Windows 10 machine instead of a windows server 2019 and everything works.
As for the user administrative information, the user logged in that is running Jenkins is both the "administrator" and the "hyper-v administrator".
These are some of the references I used to debug and I'm not able to find out what the problem is:
Remote Access With PowerShell and Jenkins, but I'm not able to figure out how exactly this works.
Running Powershell scripts using Jenkins
PowerShell: error executing command using Invoke-Command?
EDITS:
I found a way around this issue. Please mind that this isn't the definite solution but a work around.
Instead of running Invoke-Command -Credential $mycreds -VMName $VMName -ScriptBlock {host}, run this:
Invoke-Command -ComputerName "MyHostComputer" -ScriptBlock {Invoke-Command -Credential $mycreds -VMName $VMName -ScriptBlock {host}}
This command is essentially invoke-commanding into the host machine and use the host machine to run the Invoke-Command into the VM.
It is definitely not the perfect solution, but before anyone has a better solution I'll go with this for now.

Unable to create Azure VM using Powershell

Using PS 5. 0 on windows 10 I created an Azure Storage account and an Azure Service. Got the latest image name using the following command. But when I run the following command to create a VM I get following error:
PS Command to get the latest image:
$images = Get-AzureVMImage `
| where { $_.ImageFamily -eq “Windows Server 2012 Datacenter” } `
| Sort-Object -Descending -Property PublishedDate
$latestImage = $images[0]
$latestImage
The above command ran successfully and gave me the image name as: a699494373c04fc0bc8f2bb1389d6106__Windows-Server-2012-R2-20171017-en.us-127GB.vhd that I used in the following command for creating a VM.
PS command to create VM:
New-AzureVMConfig -Name "Server15" -InstanceSize ExtraSmall -ImageName "a699494373c04fc0bc8f2bb1389d6106__Windows-Server-2012-R2-20171017-en.us-127GB.vhd" | Add-AzureProvisioningConfig -Windows -AdminUsername "MyAdmin" -Password "MyPsswd" | New-AzureVM -ServiceName "MyServiceName"
Error:
WARNING: No deployment found in service: 'MyServiceName'.
New-AzureVM : BadRequest: OSImage a699494373c04fc0bc8f2bb1389d6106__Windows-Server-2012-R2-20171017-en.us-127GB.vhd
not found. If you are using a VM image, it must be specified as VMImageName for the role, not as SourceImageName for
OSVirtualHardDisk.
OperationID : '498779aecff53369ac9e793da15c16c3'
At line:1 char:250
+ ... d "D7v.oeiue4ieiur" | New-AzureVM -ServiceName "MyServiceName"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : CloseError: (:) [New-AzureVM], ComputeCloudException
+ FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.ServiceManagement.IaaS.PersistentVMs.NewAzureVMCommand
Your script works for me, here is the output:
PS C:\Users\jason> New-AzureVMConfig -Name "Server16" -InstanceSize ExtraSmall -ImageName "a699494373c04fc0bc8f2bb1389d6106__Windows-Server-2012-R2-20171017-en.us-127GB.vhd" | Add-AzureProvisioningConfig -Windows -AdminUse
rname "jason" -Password "xxxxxxx" | New-AzureVM -ServiceName "jasontest321"
OperationDescription OperationId OperationStatus
-------------------- ----------- ---------------
New-AzureVM 05a8d386-ac4b-3843-8fe4-1018325112a3 Succeeded
Please check your Azure PowerShell version, for now the latest version is 5.0.1, my Azure PowerShell version is 4.4.1, that script works fine, maybe we should upgrade your Azure PowerShell.
We can download Azure PowerShell 5.0.1 installer to your Windows 10 and install it, then test it again.
More information about Azure PowerShell Version, please refer to this link.
Hope this helps.

Unable to install AD-Domain-services on VM

I trying to build out a SharePoint 2016 Dev/test farm in Azure using PowerShell, starting with a DS server
Anyway, I have created my VM, created virtual network, public IP, NIC etc
DS VM is configured for RDP
I am getting stuck on installing the AD Domain Services
Install-WindowsFeature AD-Domain-Services -IncludeManagementTools
Success Restart Needed Exit Code Feature Result
------- -------------- --------- --------------
False Maybe Failed {}
Install-WindowsFeature : The WinRM client cannot process the request because the server name cannot be resolved.
At line:1 char:1
+ Install-WindowsFeature -ComputerName adVm AD-Domain-Services -Include ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : DeviceError: (Microsoft.Manag...rDetailsHandle):CimException) [Install-WindowsFeature],
Exception
+ FullyQualifiedErrorId : UnSupportedTargetDevice,Microsoft.Windows.ServerManager.Commands.AddWindowsFeatureComman
d
I have installed Remote Server Administration Tools for Windows 10
Started WInRM
Set-Item -Path WSMan:\localhost\Client\TrustedHosts -Value myVM
Q: Should I try to use the AD DS Deployment Commandlets directly from my win10 client

How to invoke Powershell version 2 on remote computer via Invoke-Command

I'm trying to remotely setup websites on web servers using powershell. The web servers I'm attempting to configure are Windows Server 2008 R2 SP1 which has powershell v2 on it by default.
To make things easier, I'm using the Snapin "WebAdministration".
Whenever I attempt to invoke a the following command:
PS C:\p4\eacp4wireframe\ReleaseEngineering\DL_Powershell\Infrastructure\PowerShell\IIS> Invoke-Command -ComputerName web4 -Credential $admin -ScriptBlock {add-pssnapin WebAdministration; Get-Website}
No snap-ins have been registered for Windows PowerShell version 2.
+ CategoryInfo : InvalidArgument: (WebAdministration:String) [Add-PSSnapin], PSArgumentException
+ FullyQualifiedErrorId : AddPSSnapInRead,Microsoft.PowerShell.Commands.AddPSSnapinCommand
I get the dreaded "No snap-ins have been registered for Windows PowerShell version 2" error.
Logically, I check the version of powershell by running this command:
PS C:\ Invoke-Command -ComputerName web4 -Credential $admin -ScriptBlock {(Get-Host).version}
Major Minor Build Revision PSComputerName
----- ----- ----- -------- --------------
1 0 0 0 web4
I can remotely login to the web server and run the Powershell commands fine.
Any ideas?
That version number is the version number of the host implementation used by remoting e.g.:
C:\PS> Invoke-Command . {Get-Host | Get-Member}
TypeName: System.Management.Automation.Internal.Host.InternalHost
You have to be using at least the PowerShell 2.0 engine because that is when PowerShell Remoting was introduced. It is more likely that you're invoking the 64-bit PowerShell remoting endpoint and you have snapins that either haven't been registered for the 64-bit PowerShell or won't run in 64-bit PowerShell (or vice versa).
If you need to invoke the 32-bit remoting endpoint try this:
C:\PS> Invoke-Command . {[intptr]::size} -ConfigurationName Microsoft.PowerShell32
4