Changing IP of remote server with Powershell gives disconnection error - powershell

I am trying to remotely invoke a command on a server and change it's IP, amongst other settings. I got the following line of code:
Invoke-Command -ComputerName $currentIP {`
$wmi = Get-WmiObject Win32_NetworkAdapterConfiguration -Filter "ipenabled = 'true'";`
$wmi.SetDNSServerSearchOrder($DNSServers);`
$wmi.SetGateways($Defaultgateway);`
$wmi.EnableStatic($newIP,"255.255.255.0")} -Credential $cred
Every setting is applied but at the end of the script it starts going:
The network connection to ###.##.###.## has been interrupted. Attempting to reconnect for up to 4 minutes...
And continues to fail the connection, obviously because the IP has changed. But am I issuing no more commands after the IP is changed. So why does this occur and how can I stop it?

What you are seeing is expected behaviour as WinRM has no idea that the IP is being changed and during the ScriptBlock execution the IP changes which results in connection interrupted
For smoother connection closing, you can run Invoke-Command using -AsJob parameter so that it won't be interrupted eg:
invoke-command -ComputerName 192.168.56.103 -Credential administrator -AsJob -ScriptBlock {$wmi = Get-WmiObject Win32_NetworkAdapterConfiguration -Filter "ipenabled = 'true'";$wmi.SetDNSServerSearchOrder("8.8.8.8");$wmi.SetGateways("1.1.1.1");$wmi.EnableStatic("192.168.56.104","255.255.255.0")}

Related

Couldn't use Get-WinEvent from remote computer in VLAN

The remote computer are Win-10 VM in a VLAN.
We only have a few ports open in VLAN, including 3389 for Remote Desktop, 5985 & 5986 for powershell.
Remote Desktop works well.
But I couldn't to use powershell to remote debug on those computers,
If I run
Get-WinEvent -LogName System -Credential domain\test_user -ComputerName 10.100.155.1
I get this error
Get-WinEvent : The RPC server is unavailable
If I use invoke-command to execute the same script,
Invoke-Command -ComputerName 10.100.155.1 -Credential domain\test_user -ScriptBlock {Get-WinEvent -LogName System -Credential domain\test_user -ComputerName 10.100.155.1}
I will get another error:
[10.100.155.1] Connecting to remote server 10.100.155.1 failed with the following error message : Access is denied.
I have tried many solutions on internet, unfortunately, none is working. For example, I have checked if the services are running, if the firewall allows remote event management on remote computer, they looks alright.
Any idea where could be wrong?
Your problem is two-fold.
You cannot use WinRM (Invoke-Command) with an IP address. It uses Kerberos and Kerberos requires a DNS name.
You're passing your credentials and computername twice.
This should work without a problem:
$InvokeArgs = #{
ComputerName = 'Computername.domain.com'
Credential = (Get-Credential -Credential domain\test_user)
ScriptBlock = { Get-WinEvent -LogName System }
}
Invoke-Command #InvokeArgs
Access Denied is an Authentication Issue, double check your username and password.
I was working on a similar problem, trying to fetch count of system logons. Here's what worked for me:
$fetchEvents = { Get-WinEvent -FilterHashtable #{
Logname='system'
ProviderName='Microsoft-Windows-Winlogon'
StartTime=(get-date).AddDays(-10)
ID = 7001
} | Format-Table -Property TimeCreated, UserID, ID, MachineName }
Invoke-Command -ComputerName $ServerList -Credential $creds -ScriptBlock $fetchEvents

Get-WmiObject doesn't work with IP but with FQDN

I have the following PowerShell script.
Code:
$User = "DOMAIN\user"
$PWord = ConvertTo-SecureString -String "somePassword" -AsPlainText -Force
$Credential = New-Object -TypeName "System.Management.Automation.PSCredential" -ArgumentList $User, $PWord
$query=...
Get-WmiObject -Computer 192.168.172.10 -Class Win32_ComputerSystem -ErrorAction Stop # Fails
Get-WinEvent -FilterXML $query -ComputerName 192.168.172.10 -Credential $Credential -ea stop # Works
Situation: I'm on a AD server with an IP like 192.168.1.1 and executing my script. [AD has access rights for all subnets and there is no firewall blocking access]
Issue: I want to query the following computer: server1 with ip 192.168.172.10 then this:
Get-WmiObject -Computer 192.168.172.10 -Class Win32_ComputerSystem -ErrorAction Stop # Fails
fails with an "RPC-Server is unavailable" error but this:
Get-WmiObject -Computer server1 -Class Win32_ComputerSystem -ErrorAction Stop # Works
works and this works too:
Get-WinEvent -FilterXML $query -ComputerName 192.168.172.10 -Credential $Credential -ea stop # Works
The server is in the same domain like the AD and Windows Firewall is for testing purposes disabled.
And a different server "server2" with ip 192.168.172.11 is working both ways with FQDN and ip.
Does anyone have an idea why in some cases (5 out of hundrets) the Get-WmiObject fails with ip but works with FQDN?
I searched about similar issues but all are about WinRM and are using commands like Invoke-Command. For sure WinRM first needs to be configured right in that case, but as far as I understood Get-WmIObject does not need WinRM. (I have not done any configuration tasks on all the computers).
The issue what you are facing is because of the reverse DNS records.
In your case, you might have multiple RDNS records for the same IP, causing the problem to be intermittent.
Check your reverse lookup zone and the the corresponding PTR records.
That should solve your issue.
Hope it helps.

How to list out disk-info?

Edited after some development.
I'm trying to make a script that finds all computers in an Organizational Unit (in Active Directory), and lists out size of the drive and amount of free space available.
This is what I got now:
$ou = Get-ADOrganizationalUnit -Properties * -Identity 'ou=Brukere,DC=GGR11,DC=local'
$RemServer = "xxx.xxx.xxx.xxx" #AD IP
$s = new-pssession -computer $RemServer -Credential GGR11.local\administrator #Credential = navn på domenet\domene administrator
$computers = Invoke-Command -Session $s -ScriptBlock {Get-ADComputer -Filter * -Properties name } -ArgumentList $ou
foreach ($i in $computers){
#Finner diskbruk for en maskinen
$disk = Get-WmiObject Win32_LogicalDisk -ComputerName $i -Filter "DeviceID='C:'" |Select-Object Size,FreeSpace
$disk.Size / 1GB
$disk.FreeSpace / 1GB
}
This gives me an error:
Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
The firewall on both the server and client is down, and i can share files between the two.
DCOM is enabled on both server and target PC.
Default Authntication level: Connect
Default Impersonation level: Identify
The questions:
Can anyone please look over the script? Is there something I have done wrong?
What can I do to get rid of the error?
Quoting from the WMI Troubleshooting Guide:
Error Possible Issues Solution
0x800706BA - RPC Server The computer really doesn't Connecting to Vista: netsh
Unavailable exist advfirewall firewall set
The Windows Firewall is rule group="windows
Firewall issue or server blocking the connection management instrumentation
not available. (wmi)" new enable=yes
Connecting to downlevel:
Allow the "Remote
Administration" rule in
Windows Firewall.
So, check which host $i is causing the error and double-check that the host is actually running and that the Windows Firewall is either disabled or has the abovementioned exceptions configured. Check if you can connect to Port 135/tcp on the remote host, for instance with telnet
telnet a.b.c.d 135

Powershell (Version 2.0) remote execution of services with credentials

I want to start/stop apache and mysql services on remote machine by using powershell version 2.0 (Windows Server 2008). I found syntax for remote execution as follow:
(Get-WmiObject -Computer myCompName Win32_Service -Filter "Name='myServiceName'").InvokeMethod("Stop-Service",$null)
But I have to provide credentials (DOMAIN_NAME\USERNANE and PASSWORD) also for this exceution. I am new to powershell and need help for correct syntax (example will be easy to understand and implement).
Get-WMIObject accepts the -Credential parameter. You shouldn't be keeping your credentials in plain text in your script, so you'll want to prompt for them.
$creds = get-credential;
(Get-WmiObject -Computer myCompName Win32_Service -Filter "Name='myServiceName'" -credential $creds).InvokeMethod("Stop-Service",$null)
If you have PSRemoting enabled on the remote system, you can do this without WMI.
$creds = get-credential;
Invoke-Command -computername myCompName -credential $creds -scriptblock {(get-service -name myServiceName).Stop()};
Update based on comments
Since you're running this as a scheduled job, you should not be storing or prompting for credentials at all. Configured the scheduled job itself (via Scheduled Tasks) to run under the required user account, then either of the following should work:
# Your original code
(Get-WmiObject -Computer myCompName Win32_Service -Filter "Name='myServiceName'").InvokeMethod("Stop-Service",$null)
# If you have remoting enabled
Invoke-Command -computername myCompName -scriptblock {(get-service -name myServiceName).Stop()};

Get Process StartTime from a remote server using Powershell

I'm using following command to get the start time of a windows process. This is to get the running time of a process to terminate if it running too long.
$ProcessStartTime =(Get-Process $WinProcess -computer $computer).StartTime (Not working)
above code not returning Start Time value from a remote server ( it can access other process information). But it getting values for a local process with following command.
$ProcessStartTime =(Get-Process $WinProcess).StartTime (Working)
Can some one help me.
You can use wmi for this job:
gwmi win32_process -computername $computer|
? { $_.name -eq "powershell.exe" } |
% { $_.ConvertToDateTime( $_.CreationDate )}
i've the same result as you, but you can create a new session on the remote computer then use invoke-command to run your script :
$sess=new-pssession $computer
$ProcessStartTime =invoke-command -session $sess -ScriptBlock{ (Get-Process $WinProcess).StartTime}