MDT Module Updating Media through JEA Endpoint fails adding BCD entry - powershell

I am running into an issue with remotely updating MDT offline media on a JEA endpoint. The error has something to do with permissions passed to BCDEdit and the virtual account created by JEA (WinRM User...). BCDEdit returns
An error occurred while attempting the specified create operation. This security ID may not be assigned as the owner of this object.
when trying to update the BCD file with the x64 boot config.
Command:
Invoke-Command -ComputerName $DeploymentServerName -ConfigurationName MDTUpdate -ScriptBlock {
New-PSDrive -Name "DS002" -PSProvider MDTProvider -Root "$Using:LocalDeploymentShareFolder" -ErrorAction Stop
Update-MDTMedia -Path "DS002:\Media\MEDIA001" -Verbose
} -Credential $MDTCreds -ErrorAction Stop
Command that MDT module runs:
'C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Deployment Tools\AMD64\BCDBoot\bcdedit.exe' -store "C:\MyVMs\MDT\USB\Content\Boot\bcd" /create "{f31cce1a-e314-4481-9ac9-e519f65dff65}" -d "Litetouch Boot [MEDIA001] (x64)" -application OSLOADER
Error from JEA Transcript:
VERBOSE: Error detected running command: 'C:\Program Files (x86)\Windows Kits\10\Assessment and Deployment Kit\Deployment Tools\AMD64\BCDBoot\bcdedit.exe -store "C:\MyVMs\MDT\USB\Content\Content\Boot\bcd" /create "{f31cce1a-e314-4481-9ac9-e519f65dff65}" -d "Litetouch Boot [MEDIA001] (x64)" -application OSLOADER' Exit code is: 1
VERBOSE: Error text is: An error occurred while attempting the specified create operation. This security ID may not be assigned as the owner of this object.
Update-MDTMedia : BcdEdit returned an error.
At line:5 char:9
+ Update-MDTMedia -Path "DS002:\Media\MEDIA001" -Verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (MEDIA001:String) [Update-MDTMedia], DeploymentPointException
+ FullyQualifiedErrorId : BcdEditError,Microsoft.BDD.PSSnapIn.GenerateMDTMedia
Relevant information from session config:
#{
SchemaVersion = '2.0.0.0'
SessionType = 'Default'
ExecutionPolicy = 'Unrestricted'
LanguageMode = 'FullLanguage'
TranscriptDirectory = 'C:\JEA\Transcripts'
RunAsVirtualAccount = $true
RoleDefinitions = #{
'ExampleDomain\ExampleUserOrGroup' = #{
'RoleCapabilities' = 'MDTUpdate'
}
}
}
Relevant content from role config:
#{
ModulesToImport = 'C:\Program Files\Microsoft Deployment Toolkit\Bin\MicrosoftDeploymentToolkit.psd1'
VisibleCmdlets = 'Get-Command','Out-Default','Exit-PSSession','Measure-Object','Select-Object','Get-FormatData','Start-Transcript','Stop-Transcript','Import-Module','Get-Module','New-PSDrive','Write-Output','Update-MDTDeploymentShare','Remove-Item','Update-MDTMedia','New-Item','Remove-PSDrive'
VisibleProviders = 'FileSystem', 'MDTProvider'
VisibleExternalCommands = 'bcdedit.exe'
}
How can I give BCDEdit the proper permissions when running under the virtual account? Or do I have to drop JEA and give a service account local admin rights and run it under the default PSSession?

The thing that comes to mind, is make sure that the group that the account is a part of, has more than just Read-Only permissions. I've had a case where I could run any powershell command, but when it came to invoking a non-powershell native program, it would give me permission issues.
The only other thing besides that is to use a runas within the script block, but that kinda goes against the whole purpose of JEA.

Related

Invoke-AzVMRunCommand and Start-Process under specific user on remote VM using Azure Runbook

I need to run Start-Process on a remote VM with specific user account using Azure Powershell Runbook
function Install-Postgres {
$username = "aact-import-vm1\aact-importer"
$password = "ChangeMe!"
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList `
#($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
write-output $cred
# run pg installer
Start-Process "C:\Program Files\WindowsPowerShell\Modules\Install-Postgres\postgresql.exe" -ArgumentList `
"--mode unattended", "--unattendedmodeui none",`
"--prefix `"C:\Program Files\PostgreSQL\10`"", "--datadir `"C:\Program Files\PostgreSQL\10\data`"",
"--superpassword `"ChangeMe!`"",`
"--servicename `"postgres`"", "--serviceaccount `"postgres`"", "--servicepassword `"ChangeMe!`""`
-Wait -Credential $cred;
}
$script = Get-Content Function:\Install-Postgres
Out-File -FilePath Install.ps1 -InputObject $script
#Note that the -ScriptPath should not point to the remote path(in remote vm), it should point to the local path where you execute the command Invoke-AzureRmVMRunCommand
$output = Invoke-AzVMRunCommand -ResourceGroupName $resourceGroupName -Name $vmName -CommandId 'RunPowerShellScript' -ScriptPath Install.ps1
write-output $output.Value
#after execution, you can remove the file
Remove-Item -Path Install.ps1
The script above produces the following error:
Start-Process : This command cannot be run due to the error: Access is denied.
If I run the script above without specific credentials the postgres installer produces this error in the log:
Executing icacls "C:\Windows\Temp/postgresql_installer_1ef9b3f2c6" /T /Q /grant "WORKGROUP\aact-import-vm1$:(OI)(CI)F"
Script exit code: 1332
Script output:
Successfully processed 0 files; Failed processing 1 files
Script stderr:
WORKGROUP\aact-import-vm1**$**: No mapping between account names and security IDs was done.
Please notice that there is symbol $ instead of user name.
However, if I run it on the VM it works fine and produces this line in the log:
Executing icacls "C:\Users\aact-importer\AppData\Local\Temp\2/postgresql_installer_2662c862ff" /T /Q /grant "aact-import-vm1\aact-importer:(OI)(CI)F"
Script exit code: 0
As far as I can see, If I run runbook script remotely without credentials it runs under NTAUTHORITY\SYSTEM that's why there is symbol $ instead of user name in the postgres installer log. If I run it locally it uses proper user and everything works fine.
The question is: how can I specify a user account to run Start-Process on the remote VM?
Same question on msdn https://social.msdn.microsoft.com/Forums/en-US/a7fa0ca8-5cba-42bb-8076-9a8d4a654beb/invokeazvmruncommand-and-startprocess-under-specific-user-on-remote-vm-using-azure-runbook?forum=azureautomation#a7fa0ca8-5cba-42bb-8076-9a8d4a654beb
For those who are interested:
After investigation with MS support they confirmed that runbook (not hybrid) always runs under NTAUTHORITY\SYSTEM

How can I connect to remote systems using PowerShell inside a Nano Server Docker container, specifically build 1809?

Background
I have a .NET application that I would like to install inside a Nano Server Docker container, specifically build 1809. The app is basically a REST server which will receive a REST request and depending on the contents of the JSON, invoke a particular PowerShell cmdlet on a particular remote system and return the results in JSON format.
I was able to create a Nano Server Docker container with both PowerShell and .NET Core installed. However, I ultimately realized that there is no WinRM installed on the container and therefore it is impossible to invoke remote PowerShell cmdlets.
My host system is Windows Server 2019 Datacenter, Version 1809 (OS Build 17763.379). I am using Docker Desktop for Windows (Version 2.0.0.3) with Windows containers enabled.
Dockerfile
Here is the Dockerfile I am using. I created it by combining portions of the Dockerfile from here and here.
# escape=`
# Args used by from statements must be defined here:
ARG fromTag=1809
ARG InstallerVersion=nanoserver
ARG InstallerRepo=mcr.microsoft.com/powershell
ARG NanoServerRepo=mcr.microsoft.com/windows/nanoserver
# Use server core as an installer container to extract PowerShell,
# As this is a multi-stage build, this stage will eventually be thrown away
FROM ${InstallerRepo}:$InstallerVersion AS installer-env
# Arguments for installing PowerShell, must be defined in the container they are used
ARG PS_VERSION=6.2.0
ARG PS_PACKAGE_URL=https://github.com/PowerShell/PowerShell/releases/download/v$PS_VERSION/PowerShell-$PS_VERSION-win-x64.zip
SHELL ["pwsh", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"]
ARG PS_PACKAGE_URL_BASE64
RUN Write-host "Verifying valid Version..."; `
if (!($env:PS_VERSION -match '^\d+\.\d+\.\d+(-\w+(\.\d+)?)?$' )) { `
throw ('PS_Version ({0}) must match the regex "^\d+\.\d+\.\d+(-\w+(\.\d+)?)?$"' -f $env:PS_VERSION) `
} `
$ProgressPreference = 'SilentlyContinue'; `
if($env:PS_PACKAGE_URL_BASE64){ `
Write-host "decoding: $env:PS_PACKAGE_URL_BASE64" ;`
$url = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($env:PS_PACKAGE_URL_BASE64)) `
} else { `
Write-host "using url: $env:PS_PACKAGE_URL" ;`
$url = $env:PS_PACKAGE_URL `
} `
Write-host "downloading: $url"; `
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12; `
New-Item -ItemType Directory /installer > $null ; `
Invoke-WebRequest -Uri $url -outfile /installer/powershell.zip -verbose; `
Expand-Archive /installer/powershell.zip -DestinationPath \PowerShell
# -------------------------------------------------------------------------------------------------------------------------------------------------------
# Retrieve .NET Core SDK
USER ContainerAdministrator
ENV DOTNET_SDK_VERSION 2.2.401
RUN Invoke-WebRequest -OutFile dotnet.zip https://dotnetcli.blob.core.windows.net/dotnet/Sdk/$Env:DOTNET_SDK_VERSION/dotnet-sdk-$Env:DOTNET_SDK_VERSION-win-x64.zip; `
$dotnet_sha512 = 'ed83eb5606912cd78d7696fbdc8e8074afa95fda84eec57b078d7371848ad15fe91aaf521b85e77c69b844a7b036a2c0b7b6cac87a8e356643980d96b689af93'; `
if ((Get-FileHash dotnet.zip -Algorithm sha512).Hash -ne $dotnet_sha512) { `
Write-Host 'CHECKSUM VERIFICATION FAILED!'; `
exit 1; `
}; `
`
Expand-Archive dotnet.zip -DestinationPath dotnet; `
Remove-Item -Force dotnet.zip
# -------------------------------------------------------------------------------------------------------------------------------------------------------
# Install PowerShell into NanoServer
FROM ${NanoServerRepo}:${fromTag}
# Copy PowerShell Core from the installer container
ENV ProgramFiles="C:\Program Files" `
# set a fixed location for the Module analysis cache
LOCALAPPDATA="C:\Users\ContainerAdministrator\AppData\Local" `
PSModuleAnalysisCachePath="$LOCALAPPDATA\Microsoft\Windows\PowerShell\docker\ModuleAnalysisCache" `
# Persist %PSCORE% ENV variable for user convenience
PSCORE="$ProgramFiles\PowerShell\pwsh.exe" `
# Set the default windows path so we can use it
WindowsPATH="C:\Windows\system32;C:\Windows"
# Set the path
ENV PATH="$WindowsPATH;C:\Program Files\PowerShell;C:\Program Files\dotnet;"
COPY --from=installer-env ["\\PowerShell\\", "$ProgramFiles\\PowerShell"]
# intialize powershell module cache
RUN pwsh `
-NoLogo `
-NoProfile `
-Command " `
$stopTime = (get-date).AddMinutes(15); `
$ErrorActionPreference = 'Stop' ; `
$ProgressPreference = 'SilentlyContinue' ; `
while(!(Test-Path -Path $env:PSModuleAnalysisCachePath)) { `
Write-Host "'Waiting for $env:PSModuleAnalysisCachePath'" ; `
if((get-date) -gt $stopTime) { throw 'timout expired'} `
Start-Sleep -Seconds 6 ; `
}"
# -------------------------------------------------------------------------------------------------------------------------------------------------------
COPY --from=installer-env ["/dotnet", "/Program Files/dotnet"]
# -------------------------------------------------------------------------------------------------------------------------------------------------------
USER ContainerAdministrator
EXPOSE 80/tcp
EXPOSE 5985/tcp
EXPOSE 5986/tcp
EXPOSE 7777/tcp
EXPOSE 7778/tcp
CMD ["pwsh.exe"]
Docker Commands
Here are the Docker commands I am using to create and access the Docker container (note the directory contains a single Dockerfile with the contents above):
docker build C:\powershell-nanoserver1809-with-dotnet-2.2.401
docker create -t --name NanoServerHelloWorld -h NanoServer -i <ID_RETURNED_FROM_PREVIOUS_COMMAND>
docker start -i NanoServerHelloWorld
PowerShell and WinRM commands that fail
On other systems I can use the following PowerShell code to create a CimSession to a remote system and subsequently invoke a PowerShell cmdlet:
$u = "REMOTE_DOMAIN\REMOTE_USERNAME";
$pw = "REMOTE_PASSWORD";
$secStr = New-Object -TypeName System.Security.SecureString;
$pw.ToCharArray() | ForEach-Object {$secStr.AppendChar($_)};
$Cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $u, $secStr;
$Session = New-CimSession -ComputerName 172.27.0.114 -Authentication Negotiate -Credential $Cred -OperationTimeoutSec 900
But in this container I get this error message:
New-CimSession : FAILED
At line:1 char:12
+ $Session = New-CimSession -ComputerName 172.27.0.114 -Authentication ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [New-CimSession], CimException
+ FullyQualifiedErrorId : Microsoft.Management.Infrastructure.CimException,Microsoft.Management.Infrastructure.CimCmdlets.NewCimSessionCommand
Further, if I try to configure WinRM in anyway, I get the following (from cmd):
C:\>winrm set winrm/config/client #{TrustedHosts="*"}
'winrm' is not recognized as an internal or external command,
operable program or batch file.
Also, if I look at services on the container, I don't see WinRM:
PS C:\> Get-Service
Status Name DisplayName
------ ---- -----------
Running cexecsvc Container Execution Agent
Running CryptSvc Cryptographic Services
Running DcomLaunch DCOM Server Process Launcher
Running Dhcp DHCP Client
Running DiagTrack Connected User Experiences and Teleme…
Running Dnscache DNS Client
Running EventLog Windows Event Log
Stopped KeyIso CNG Key Isolation
Stopped LanmanServer Server
Running LanmanWorkstation Workstation
Stopped lmhosts TCP/IP NetBIOS Helper
Stopped mpssvc Windows Defender Firewall
Stopped Netlogon Netlogon
Stopped NetSetupSvc Network Setup Service
Running nsi Network Store Interface Service
Stopped Power Power
Running ProfSvc User Profile Service
Running RpcEptMapper RPC Endpoint Mapper
Running RpcSs Remote Procedure Call (RPC)
Running SamSs Security Accounts Manager
Running Schedule Task Scheduler
Stopped seclogon Secondary Logon
Running SystemEventsBroker System Events Broker
Running TimeBrokerSvc Time Broker
Get-Service : Service 'TrustedInstaller (TrustedInstaller)' cannot be queried due to the following error:
At line:1 char:1
+ Get-Service
+ ~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (System.ServiceProcess.ServiceController:ServiceController) [Get-Service], ServiceCommandException
+ FullyQualifiedErrorId : CouldNotGetServiceInfo,Microsoft.PowerShell.Commands.GetServiceCommand
Stopped TrustedInstaller TrustedInstaller
Running UserManager User Manager
Stopped VaultSvc Credential Manager
Stopped WerSvc Windows Error Reporting Service
Stopped WinHttpAutoProxyS… WinHTTP Web Proxy Auto-Discovery Serv…
Stopped wisvc Windows Insider Service
Question
Is there a way to get WinRM installed and working on a Nano Server Docker container build 1809? If not, is there some workaround to connect to remote systems with PowerShell to invoke PowerShell cmdlets?
Perhaps there is some special Docker command I am missing, or some other Nano Server image available which has this missing feature?
Thanks very much in advance.

getting error while copying file to remote location using powershell scripts in gitlab runner

I am setting up a GitLab CI/CD pipeline to copy the war file using PowerShell copy-item function. I am getting below error in the pipeline. the user is already an administrator on the gitlab runner computer.
[servername] Connecting to remote server name failed with the
following error message: Access is denied. For more information, see
the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (servername:String) [], PSRemotingT ransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionStateBroken ERROR: Job failed: exit status 1
Here is my script in .yml file.
GitLab Runner registered in windows server.
Here is my script in .yml file.
envvariable_username - Environment variable configured in gitlab CI/CD settings page
$envvariable_password - Environment variable configured in gitlab CI/CD settings page
- powershell Invoke-Command -ComputerName computer_name -argumentlist $envvariable_username,$envvariable_password -ScriptBlock {
$password = convertto-securestring -String $envvariable_password -AsPlainText -Force
$mycred = new-object -typename System.Management.Automation.PSCredential $envvariable_username, $password
New-PSDrive -Name "s" -PSProvider FileSystem -root "\\\\computer_name\\share" -Credential $mycred
New-PSDrive -Name "z" -PSProvider FileSystem -root "\\\\computer_name\\backup" -Credential $mycred
Copy-Item -Path "s:\\sample.war" -Destination "z:\\sample.war"
}
expected to copy .war file from one server location to another server location
Looking at your script, you try to execute a script block on a remote server without specifying credentials. That means that either the server has no restrictions or you assume that both servers belong to the same domain, so kerberos will be utilized.
In my experience, when the second is the case, most people forget to evaluate on who's behalf is the script executing. Keep in mind that a process inherits the user context of the parent process unless otherwise specified.
That would mean that the user running your script doesn't have the necessary access to the remote server. You can always evaluate this by first doing this $env:USERDOMAIN + "\" + $env:USERNAME
For example a line in your yaml
- powershell $env:USERDOMAIN + "\" + $env:USERNAME
So when you debug something from a console that you launched with your user, then you don't have 100% replication of the conditions as you are forgetting the most important aspect of any process, that is the logon user.
Then, if this works, I've noticed that from the remote server you are trying to access another remote location. I notice that you are specifying credentials for this part if please do note that if from within a remote session, you try to access any remote resource, then you need to be aware of some caveats. Please read more about them hereand especially the one specific to the double hop.
As a word of advice, best way to troubleshoot scripts that utilize remote execution, is to logon on the server with the same user as with the services that runs your scripts, thus replication the conditions 100%. It is also possible to launch only the console with the credentials of another user.

remove-computer cmdlet access denied

I am trying create a script to remove a computer from a domain using remove-computer -unjoincredentials domain\admin -passthru However, I consistently receive an error stating that
remove-computer : Failed to unjoin computer 'web140127105714' from domain 'domain.com' with the following error
message: Access is denied.
At line:1 char:1
+ remove-computer -UnjoinDomainCredential domain\admin -PassThru
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (web140127105714:String) [Remove-Computer], InvalidOperationException
+ FullyQualifiedErrorId : FailToUnjoinDomain,Microsoft.PowerShell.Commands.RemoveComputerCommand
The account I am using is a domain administrator with full access. I have confirmed that the account can manually unjoin from the domian.
Some operations on the console require you to be on an elevated PowerShell session. You can start your PowerShell session as Admin by right clicking on it and choosing 'Run as Administrator'. Then run the remove-computer cmdlet in that console session. Default title of the Administrator PowerShell console is 'Administrator : Windows PowerShell'. You can identify the window that way
Sounds like the OP found his answer, so here is a powershell self elevating example for future readers. Add to the top of your scripts and it will re-launch itself elevated so we don't have to right click and 'Run As Administrator'.
$WID=[System.Security.Principal.WindowsIdentity]::GetCurrent();
$WIP=new-object System.Security.Principal.WindowsPrincipal($WID);
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator;
If ($WIP.IsInRole($adminRole)){
}else {
$newProcess = new-object System.Diagnostics.ProcessStartInfo 'PowerShell';
$newProcess.Arguments = $myInvocation.MyCommand.Definition
$newProcess.Verb = 'runas'
[System.Diagnostics.Process]::Start($newProcess);Write-Host 'Prompting for Elevation'
exit
}
#####################
# Add Scripts Below #
#####################
Write-Host 'ElevatedCodeRunsHere';
Write-Host 'Press any key to continue...'
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown')
Powershell start-process script calls a second script - how to make one script only
There is no such parameter as -unjoincredentials
http://technet.microsoft.com/en-us/library/hh849816.aspx

Intermittent errors with automation of virtual machines using Powershell

I have an intermittent problem with Powershell when automating some tests on a virtual machine.
The scenario and set up is as follows:
Server running HyperV
One virtual machine with multiple snapshots
Powershell script that restores a given snapshot, copies files over, runs a test and retrieves log files
Batch file that calls the Powershell script multiple times with different parameters
The batch file parameters specify things like which snapshot to use, which test to run, etc.
The problem is as follows:
I can run the batch and some of the tests will fail to copy files / fail to create a scheduled task / fail to retrieve log files / etc. It varies which if any (or all) sections fail. Some of the tests will work completely. If I re-run the same batch file, again some tests may fail and others will work; there is no consistency in terms of which fail and which run. Sometimes I have two adjacent tests that use the same snapshot, 1 will work and 1 won’t (see errors below).
To restore the snapshots I am using the “PowerShell Management Library for Hyper-V” from: (http://pshyperv.codeplex.com/releases)
Below is some of the code:
Powershell (minus a few functions / variable declarations / reading xml config file / reading and validating command line inputs / and other non-relevant sections):
Function ApplySnapshot
{
LogAction "Starting apply snapshot"
LogAction $("Restoring snapshot {0}" -f $ss)
#Stop a running VM, restore snapshot, start it up and connect to it
$vmstate = get-vmstate $vmname
$vmstate = $vmstate.EnabledState
if ($vmstate -ne "Stopped")
{
stop-vm $vmname -force
Start-Sleep -Second 15
}
get-vmsnapshot $vmname | where {$_.ElementName -eq $ss} | Restore-VMSnapshot -force
start-vm $vmname -force
Start-Sleep -Second 20
LogAction $("Snapshot {0} restored" -f $ss)
LogAction "End apply snapshot"
}
Function CopyFiles
{
LogAction "Start copy installation files"
$from = "\\server\folderx"
$to = "\\" + $hostname + "\C$\test"
Enter-PSSession -ComputerName $hostname -Credential $cred
Copy-Item $from $to -Recurse
LogAction "End copy installation files"
}
Function CreateSchedule ($hn, $tn, $tr, $sd, $st, $un, $pw)
{
LogAction "Starting create schedule"
Invoke-Command -ComputerName $hn -ScriptBlock {
param($hn, $tn, $tr, $sd, $st, $un, $pw)
Write-Host $("Host name: [{0}]" -f $hn);
$cmd = $("schtasks.exe /create /S ""{0}"" /tn ""{1}"" /tr ""{2}"" /sc once /sd {3} /st {4} /ru ""{5}"" /rp ""{6}"" /rl highest /V1" -f $hn, $tn, $tr, $sd, $st, $un, $pw);
Invoke-Expression $cmd;
} -ArgumentList #($hn, $tn, $tr, $sd, $st, $un, $pw)
LogAction "End create schedule"
}
...setting variables etc...
ApplySnapshot
CopyFiles
CreateSchedule -hn $hostname -tn $taskname -tr $taskrun -sd $setdate -st $settime -un $username -pw $password
Batch file:
PowerShell -Command "& C:\Auto.ps1" <...params...>
PowerShell -Command "& C:\Auto.ps1" <...params...>
PowerShell -Command "& C:\Auto.ps1" <...params...>
PowerShell -Command "& C:\Auto.ps1" <...params...>
pause
Example output:
C:\Auto>PowerShell -Command "& C:\Auto.ps1" <...params...>
WARNING: The job to Change state of VM TestVM to Stopped is still
running in the background.
You can check its progress with Test-wmiJob or Test-wmiJob -statusOnly using
the following job id:
\\Server\root\virtualization:Msvm_ConcreteJob.InstanceID="A207CEBA-F582-4A42-
BCDE-3312C7FB6DCC"
JobStarted
WARNING: The job to Change state of VM TestVM to Running is still
running in the background.
You can check its progress with Test-wmiJob or Test-wmiJob -statusOnly using
the following job id:
\\Server\root\virtualization:Msvm_ConcreteJob.InstanceID="42C31CEF-00E2-40A7-
AF70-578B0B91B05D"
JobStarted
Enter-PSSession : Connecting to remote server failed with the following error m
essage : The WinRM client cannot complete the operation within the time specifi
ed. Check if the machine name is valid and is reachable over the network and fi
rewall exception for Windows Remote Management service is enabled. For more inf
ormation, see the about_Remote_Troubleshooting Help topic.
At C:\Auto.ps1:192 char:18
+ Enter-PSSession <<<< -ComputerName $hostname -Credential $cred
+ CategoryInfo : InvalidArgument: (TestVM:String) [Enter-PSS
ession], PSRemotingTransportException
+ FullyQualifiedErrorId : CreateRemoteRunspaceFailed
[TestVM] Connecting to remote server failed with the following error messa
ge : The WinRM client cannot complete the operation within the time specified.
Check if the machine name is valid and is reachable over the network and firewa
ll exception for Windows Remote Management service is enabled. For more informa
tion, see the about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (:) [], PSRemotingTransportException
+ FullyQualifiedErrorId : PSSessionStateBroken
So, in this example, the snapshot has been successfully applied (despite the warnings). The “Enter-PSSession” error appears after the files have been copied to the virtual machine.
As a test, I tried this on a different server (also running HyperV etc etc), and I found that I still get the initial error (after the file copying stage) but I do not get the error creating the scheduled task.
All my efforts to search for information on the “Connecting to remote server failed with the following error message : The WinRM client cannot complete the operation within the time specified.” Error seem to say “make sure the machine is set up for remote use”; well I know it is because sometimes it works and if I run just an “Enter-PSSession” command by itself, I can connect.
The server(s) and virtual machine(s) are on the same domain.
I know there’s a lot to take in here, but I would really appreciate some help in how to troubleshoot / fix this problem.
Thank you
Maybe the targets are not always up when the connection attempts are being made.