Configure Remote Desktop for Administrator with PowerShell - powershell

Is it possible to configure Remote Desktop for Administrator using PowerShell without installing the "Remote Desktop Session Host" role on all our servers? We're after the RemoteDesktopServices module.
The docs here: http://technet.microsoft.com/en-us/library/cc743159.aspx say
"To allow remote connections for administrative purposes only, you do not have to install an RD Session Host server."
but all the instructions for using PowerShell seem to require the extra role. Is it necessary, and if so, what the implications, as it seems to be a much broader set of functionality?

Using wmi you can do it without RDSH (copy&paste from here )
$RDP = Get-WmiObject -Class Win32_TerminalServiceSetting `
-Namespace root\CIMV2\TerminalServices `
-Computer $Computer `
-Authentication 6 `
-ErrorAction Stop
$result = $RDP.SetAllowTsConnections(1,1)
if($result.ReturnValue -eq 0) {
Write-Host "$Computer : Enabled RDP Successfully"
"$Computer : RDP Enabled Successfully" | Out-File -FilePath $SuccessComps -Append
} else {
Write-Host "$Computer : Failed to enabled RDP"
"$Computer : Failed to enable RDP" | Out-File -FilePath $FailedComps -Append
}

Related

Use PowerShell to install Windows Updates in vSphere

I have a cluster of vSphere windows clients approximately 100 that I want to remotely automate windows updates on weekly. I have listed all the windows machine out in text file on my desktop. I have run the PSWindowsUpdate module on my local windows10 machine with command:
Install-Module -Name PSWindowsUpdate and then executed the below script successful for my local machine to run windows updates.
#Import-Module PSWindowsUpdate
#Remove-Item -Path C:\Scripts\status.tx
#Start-Transcript -Path C:\Scripts\status.txt
#$Updates = "Critical Updates", "Security Updates"
#Get-WUInstall -AcceptALL- Verbose -IgnoreReboot -Category $Updates
#Write-Host "Done"
#Stop-Transcript
#Start-Sleep -s 120
#Restart-Computer -Force -Confirm:$false
-- after pc restarts run as PS As Administrator
#Get-WindowsUpdate
However, I am not a expert at PowerShell so, I do not know what to additionally script to accomplish the task of remotely updating 100 or so windows clients in vSphere.
Any suggestion would be appreciated.
You can try with the invoke-command. You can create a server list from a DC:
$Servers = Get-ADObject -Filter * -Properties Name,OperatingSystem | Where-Object OperatingSystem -like '*Server*'
And use this list with a loop like this
ForEach($_ in $Servers)
{
Invoke-Command -ScriptBlock {Get-WUInstall -AcceptALL- Verbose -IgnoreReboot -Category $Updates } -ComputerName $_.Name -ErrorAction SilentlyContinue
}

Powershell remotely execute commands

I am having an issue trying to execute the command remotely. First, the command is trying to copy an executable to the remote system and I think that's where my issue is because you can't access \hostname\C$\Windows\Temp straight, you must connect to C$ first then go to C:\Windows\Temp
That being said, I tried that as well ($Dest = "C$"), and still not working
FYI: The folder might or might not exist in the client
$SetupFolder = "C$\Windows\Temp\Logs"
$Path = "C:\Windows\Temp\Logs\Install.exe"
$Dest = "C$"
# Remote run the install for each system
foreach ($System in $SystemList) {
if (test-Connection -Cn $System -quiet) {
Copy-item $Package -Destination \\$System\$SetupFolder -recurse -Force
if (Test-Path - Path $Path) {
Invoke-Command -ComputerName $System -ScriptBlock {powershell.exe $Path /S} -credential $Credentials
Write-Host -ForegroundColor Green "Installation Successful on $System"
}
} else {
Write-Host -ForegroundColor Red "$System is not online, Install failed"
}
}
You could use Enter-PSSession if you cannot use Invoke-Command, this starts an interactive session with a remote computer, you will need to have permissions on the remote computer first to connect,
More information in the PowerShell documentation,
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/enter-pssession?view=powershell-7.1

PowerShell - Invoke Command on Remote Machines/Computers

There's plenty of forums/material regarding the subject line, but cannot seem to get an answer for my problem.
I'm trying to execute a script from the main server (SRV01) that will clean the temp folders on the secondary servers (SRV02, SRV03).
Here is the script:
#Set the machines on the network to run the script on
$VDST = #("SRV02", "SRV03")
#Folder locations to clean out
$TempFolder = #("C:\Windows\Temp\*", "C:\Documents and Settings\*\Local Settings\temp\*")
#This function actually performs the clean up operation
Function executeCleanUp
{
$TempFolder = $args[0]
$machineNames = $args[2]
ForEach($machine in $machineNames){
Get-PSSession -ComputerName $machine | Format-Table -Property ComputerName, InstanceID
Write-Host 'Starting Clean Up...'
#Loop through the sub folders in the registry location
ForEach($folderLocation in $TempFolder)
{
$StrInput = 'Remove-Item -Path ' + $folderLocation + ' -Force -Recurse -ErrorAction SilentlyContinue'
$action = New-ScheduledTaskAction -Execute 'PowerShell.exe' -Argument $StrInput
Register-ScheduledTask -Action $action -TaskName "CleanUp"
Start-ScheduledTask -TaskName "CleanUp"
Unregister-ScheduledTask -TaskName "CleanUp" -Confirm:$false -ErrorAction SilentlyContinue
}
}
#Execute Script on specified machines - provided in array above
Invoke-Command -ComputerName $VDST -ScriptBlock ${function:executeCleanUp} -ArgumentList $TempFolder, $VDST
After running the above, I get the error:
A specified logon session does not exist
So, I came across a forum where it was suggested to do the following:
#Remote Server (VDI)
Enable-WSManCredSSP -Role server
#Expected Output
#This computer is configured to receive credentials from a remote client computer.
#Local Machine
Enable-WSManCredSSP -Role Client -DelegatedCredentials 'SRV01'
#Expected Output
#The machine is configured to allow delegating fresh credentials to the following target(s): wsman/SRV01.
#Local Machine
#Open gpedit.msc
#Browse to Computer Configuration > Administrative Templates > System > Credentials Delegation.
#Double-click "Allow delegating fresh credentials with NTLM-only Server Authentication"
#Enable the setting
#Add the build server to the server list as WSMAN/BuildServerName.
#Example Execution:
#Invoke-Command -ComputerName <REMOTE_COMPUTER_NAME> -Authentication CredSSP -Credential <USERNAME> -ScriptBlock { #code}
I've done all this, but now I get the error:
A computer policy does not allow the delegation of the user
credentials to the target computer
Also, I am assuming the line
WSMAN/BuildServerName
should be written
WSMAN/SRV02
The 2 hop authentication issue came up because you are trying to list remote sessions with in your remote session
Get-PSSession -ComputerName $machine | Format-Table -Property ComputerName, InstanceID
If you just want to clear some files on the remote servers the code below should work with no need for CredSPP.
Setting -ErrorAction SilentlyContinue will make trouble shooting difficult, It's easier to check if the file exists before you try to delete it.
$TempFolder = $args[0]
$ComputerArray = "SRV02","SRV03"
$ScriptBlock =
{
foreach ($Folder in $TempFolders)
{
if (Test-Path -Path $TempFolder)
{
Remove-Item -Path $Folder -force
}
}
}
Invoke-Command -ComputerName $ComputerArray -ScriptBlock $ScriptBlock -ArgumentList $TempFolder
Wrong answer:
Your issue is two hop authentication.
You can't nest remote sessions with default windows settings.
While this would not be considered to be best practice, you can enable CredSSP to bypass the problem.
https://learn.microsoft.com/en-us/windows/win32/secauthn/credential-security-support-provider
https://learn.microsoft.com/en-us/powershell/module/microsoft.wsman.management/enable-wsmancredssp?view=powershell-7
Could you either log on to SVR01 to run the script or run the script against the target machines from your own computer?

How to run commands on a remote computer using PSExec and PowerShell?

I am trying to install an .exe program remotely to many workstations in the domain.
The command I am trying to run in the remote computer's PowerShell instance:
.\PsExec.exe \\$Computer /s cmd /c %SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Unrestricted -File \\FileShare\Software\DellSupportAssist.ps1
And the script I am calling in the command above:
#Retrieves a list of computers in AD.
$Computers = Get-ADComputer -Filter 'Name -like "Workstation*"' | Select-Object -ExpandProperty Name
ForEach ($Computer in $Computers) {
#Opens a remote session into the computer.
.\PsExec.exe C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe \\$Computer
#Installs Dell SupportAssist for each computer
Invoke-WebRequest -Uri "https://downloads.dell.com/serviceability/catalog/SupportAssistInstaller.exe" -OutFile "C:\Users\$env:Username\Downloads\SupportAssistInstaller.exe"
Start-Process "C:\Users\$env:Username\Downloads\SupportAssistInstaller.exe" -ArgumentList "/q" -Wait -NoNewWindow
Write-Host "Installing Dell SupportAssist on $Computer" -ForegroundColor Green
#Checks whether Dell SupportAssist was successfully installed or not
if (Get-WmiObject -Class win32_product -ComputerName $Computer | Where {$_.Name -match "Dell Support*"} | Select-Object -ExpandProperty Name) {
Write-Host "Dell SupportAssist was successfully installed on $Computer" -ForegroundColor Yellow
} else {
Write-Host "Dell SupportAssist was not successfully installed on $Computer" -ForegroundColor Red
}
exit
}
I am having the following issues:
'Target name incorrect' (for half of the computers in the domain.)
.\PsExec.exe : The term '\FileShare\Software\DellSupportAssist.ps1' is not recognized as the name of a cmdlet, function, script file, or operable (for the computers I can connect to in the domain)

How to set vm computer's name from host machine using powershell?

I found an article about Rename the guest OS to match the virtual machine name on Hyper-V to rename computer name to match the vm's name. The problem is this script has to attached on the virtual machine and it's going to be hard if I want to change it.
Is it possible to rename vm computer's name from the host machine?
Give this a try, you can run it on the host. Currently it just prints a message of the old and new vm name. I left two options (commented out) in the code to rename the machine. Keep in mind that the machines should be resolvable and preferably part of your domain (you might need to remove the domain extensions from the vm name).
Get-WmiObject -Namespace root\virtualization\v2 -Class Msvm_ComputerSystem | Where-Object {$_.ElementName -ne $env:COMPUTERNAME} | ForEach-Object {
$newName = $_.ElementName
$_.GetRelated('Msvm_KvpExchangeComponent').GuestIntrinsicExchangeItems | ForEach-Object {
if($_ -as [xml])
{
$GuestExchangeItemXml = ([XML]$_).SelectSingleNode("/INSTANCE/PROPERTY[#NAME='Name']/VALUE[child::text()='FullyQualifiedDomainName']")
if ($GuestExchangeItemXml -ne $null)
{
$vmName = $GuestExchangeItemXml.SelectSingleNode("/INSTANCE/PROPERTY[#NAME='Data']/VALUE/child::text()").Value -replace '\W','_'
$vmName = $vmName.Substring(0,[System.Math]::Min(15,$vmName.Length))
#(Get-WmiObject Win32_Computersystem -ComputerName $vmName).Rename($newName); shutdown -r -t 0
#Rename-Computer -ComputerName $vmName -NewName $newName -Restart -Force -WhatIf
Write-Host "Renaming $vmName to $newName"
}
}
}
}
Use the Rename-Computer cmdlet:
Rename-Computer -ComputerName OldServerName -NewName NewServerName -Restart -Force
Rename-Computer does not use Powershell remoting so it is possible to run even without remote commands being enabled. See the docs.
You can change the hostname in the guest if you're able to connect to the remote host over the network.
$oldname = 'foo'
$newname = 'bar'
(Get-WMIObject Win32_ComputerSystem -Computer $oldname).Rename($newname)
Restart-Computer $oldname
Here is the simple command execute it through power shell
(gwmi win32_computersystem).Rename("NewName"); shutdown -r -t 0
Here's a short one
Invoke-Command -VMName "vm name here" -ScriptBlock {
Rename-Computer -NewName "new name here"
}