Rename/unjoin a computer from a domain, that isn't on the domain - powershell

Working on a script that will be run on a clone of a VM. When cloned out, the IP settings switch from static to DHCP and the name/domain remain the same as the source. Parts of my script require that the VM be on the domain to run, however, I can't just set an open IP on the NIC, since it will then update DNS with the new IP, disable the computer object in AD and break the trust relationship.
Normally, through windows, I join a workgroup [remove from domain] and the OS is happy, just wants a reboot. I can then set the IP on the NIC, change the name and set it to join back to the domain before another reboot. I then have 2 of the same machine, different names and IP addresses without any conflicts.
I am at an impasse at getting this accomplished with PowerShell though. I can't rename or join a workgroup unless I am on the domain. I thought workflows would be the answer, but after reading a little bit on it, I am not so sure anymore.
So this is more of a workflow Q than actual code and any feedback is appreciated.

wmi commandline works and gives me a starting point.
#echo off
start /B /W wmic.exe /interactive:off ComputerSystem Where "Name='%computername%'" Call UnJoinDomainOrWorkgroup FUnjoinOptions=0
start /B /W wmic.exe /interactive:off ComputerSystem Where "Name='%computername%'" Call JoinDomainOrWorkgroup name="WORKGROUP"
start /B /W wmic.exe /interactive:off ComputerSystem Where "Name='%computername%'" Call Rename name="standaloneComputer"
shutdown.exe /r /t 0 /f

I use the following procedure when dealing with cloned Windows VMs:
Start the clone with disconnected network interface(s).
Remove non-present network adapters.
Assign new IP address(es) to the remaining network adapter(s).
$wmi = Get-WmiObject Win32_NetworkAdapterConfiguration -Filter "IPEnabled='true'"
$wmi.EnableStatic('192.168.23.42', '255.255.255.0')
$wmi.SetGateways('192.168.23.1', 1)
$wmi.SetDNSServerSearchOrder(('192.168.23.13', '192.168.23.14'))
Rename the computer and remove it from the domain.
Reboot.
Reconnect the interface(s).
Join the renamed computer back to the domain.
Note: Make sure the clone has a local admin account that you can log in with while the domain is not accessible.

Related

Required Help in RDP Automation

Below script is to Automate RDP and I am stuck with below two points:
How to map local drive as mapped drive in RDP session(tsclient) using
powershell script/command
Example like this in RDP : drivestoredirect:s:value
RDP Automation - PowerShell Script :
cmdkey /list | ForEach-Object{if($_ -like "*target=TERMSRV/*"){cmdkey /del:($_ -replace " ","" -replace "Target:","")}}
echo "Connecting to Server Name"
$Server="Server Name"
$User="Username"
$Password="Password"
cmdkey /generic:TERMSRV/$Server /user:$User /pass:$Password
mstsc /v:$Server
reg add "HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client" /v "AuthenticationLevelOverride" /t "REG_DWORD" /d 0 /f
You can't control all aspects of your connection when using mstsc.exe via command line. The information for mapping local resources in the TS session are stored in the RDP file.
If not specified, it will use the default.rdp file located in "My Documents" folder (hidden file).
If you configure the default RDP to map local resources, all subsequent connections will also have the local resources mapped... but if you change it again, it will apply to all next connections.
So a better approach will be to create one *.rdp file and use it as a template in your script:
Create Template RDP file:
Launch mstsc.exe
Configure all options as per your needs
Save the file somewhere and use it in your script (i.e C:\Temp\MyRDPtemplate.rdp)
Now, change your script in order to use this template file when connecting to a Server:
mstsc "C:\temp\MyRDPtemplate.rdp" /v:$Server
When you first connect to a Server while mapping local resources, you will receive a warning message:
If you want to avoid this message, add the following registry key before launching:
reg add "HKCU\Software\Microsoft\Terminal Server Client\LocalDevices" /v $Server /t "REG_DWORD" /d 0x4d /f
mstsc "C:\temp\MyRDPtemplate.rdp" /v:$Server
There may be a global parameter you can add to avoid this message for all Servers (like for "AuthenticationLevelOverride") but I don't know for sure.
On last word about the stored credentials... if you use cmdkey /generic:xxx, you don't need to specify the service type (TERMSRV), that's the purpose of the /generic switch. But it also works fine...
PS: Very last remark, if you want to bypass the certificate prompt (in case your server doesn't present a valid one, you should add the registry key AuthenticationLevelOverride before connecting to the Server. Also note that this key is valid for all connections.
Another choice is get a help form some 3rd-part tools for RDP.
https://github.com/VShawn/PRemoteM

Run a script after a Windows 10 (non-Domain) Reset to enable RDP

For the Reset function, I go to Settings > Updates and Security > Recovery > Reset this PC. So this is a choice that I make, and on that basis I want to choose for that system to run a script after the Reset - and we know that should be possible as we can create completely customised Windows installation ISOs that install apps and Features in a clean state, so can someone tell me how to do a quite simple things - to just get Windows to run a PowerShell script after that Reset?
Actually, I only want to run a couple of lines:
Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server'-name "fDenyTSConnections" -Value 0
Enable-NetFirewallRule -DisplayGroup "Remote Desktop"
i.e. This will enable RDP and allow me to connect remotely and continue the configuration without having to plug in a monitor and keyboard and mouse all just to run the above two commands. As per title, this is a non-Domain scenario so accessing the system as Domain Admin is not possible (and really a Domain should not be necessary, these are my systems on my local network).
The other reason that should make all of the above completely possible is that performing a Reset is not an absolute reset as it retains user information (my main user is still there with the password intact), so just enabling RDP would make everything possible post-Reset.
For reference, nothing in the following have helped me to achieve this goal so far:
Run a powershell script on a remote system with elevated permissions to enable remoting
https://interfacett.com/blogs/how-to-remotely-enable-and-disable-rdp-remote-desktop
The easiest way to do this is to download PStools from Microsoft and use psexec to give yourself remote access:
psexec \\machinename reg add hklm\system\currentcontrolset\control\terminal server /f /v fDenyTSConnections /t REG_DWORD /d 0
psexec \\machinename netsh firewall set service remoteadmin enable
psexec \\machinename netsh firewall set service remotedesktop enable
psexec will let you supply credentials with -u and -p

How can i delete the contents of the spool\PRINTERS directory remotely via powershell without WinRM

I need to be able to pass credentials through, which i have local administrator credential for the remote machine.
I only need to target one machine at a time, which will be manually specified in a function and the IP will be assigned as a $Global:var
I can use WMI-GetObject and stop/start the printer spool service, but cannot figure out a way to delete the remote files while passing credentials without using invoke, which doesnt work as WinRM is not enabled (and cannot be by policy)
Thank you for any help you can offer.
I have a test setup i can test as much as needed
also let me know if this would suit SuperUser more than StackOverflow
In the end i could not find a solution in powershell itself, so i defaulted to a co-located Batch file to handle the windows file operations and called the batch file from powershell with
start-process -Wait "cmd.exe" "/c c:\powershell\clearspool.bat"
batch file is below
#ECHO off
rem Set up the remote server ip
set User=administrator
set /p Server=Enter Server IP:
set /p Password=Enter Admin Password:
rem Mount the remote path
net use \\%Server%\c$\Windows\System32\spool %Password% /USER:%User%
rem Delete a file
del /S /F \\%Server%\c$\Windows\System32\spool\PRINTERS
rem Unmount the remote path
net use \\%Server%\c$\Windows\System32\spool /delete

psexec double backslash error

I am trying to run the following command in power shell but it keeps giving me error at the double back slash character.. what do i do!! I saw other forums and this yntax works fine for them!
$combined="C:\tools\PsExec.exe \\computer cmd.exe"
PS C:\Users\Desktop\initialutility\initutil_v2> Invoke-Expression $combined
At :line:1 char:20
+ C:\tools\PsExec.exe <<<< \\computer cmd.exe
I substituted \computer with \x.x.x.x (i.e Ip address)..still no use..
Please help!
I believe your problem lies elsewhere as double slashes work fine e.g.:
PS> $command = "c:\bin\psexec.exe \\genericpc1 hostname.exe"
PS> iex $command
PsExec v1.98 - Execute processes remotely
Copyright (C) 2001-2010 Mark Russinovich
Sysinternals - www.sysinternals.com
GENERICPC1
hostname.exe exited on genericpc1 with error code 0.
I would try running psexec.exe outside the context of Invoke-Expression and get that working first. Another issue with using psexec is that it uses your credentials if you don't specify any credentials. That means, your credentials need to work on the remote system.
Other requirements, from an article on PsExec are:
PsExec's ability to run processes remotely requires that both the
local and remote computers have file and print sharing (i.e., the
Workstation and Server services) enabled and that the default Admin$
share (a hidden share that maps to the \windows directory) is defined
on the remote system.
... impersonates the account from which you run PsExec on the local
system. Impersonation is somewhat restricted from the perspective of
security—the remote process doesn't have access to any network
resources, even those that your account typically would be able to
access. If the account in which you're running doesn't have local
administrative privileges on the remote system, the process you want
to run requires access to network resources, or you want to run a
process in a different account, then use PsExec's -u switch to provide
an alternative account name.
share (a hidden share that maps to the \windows directory) is defined
on the remote system.

netsh acl setting (need alternative method - registry settings?)

I am using inno-setup to install a program that needs to unblock port 4326 on Win7 (permit acl access) so that GET operations can be done over HTTP to port 4326.
I have a powershell script that an admin can run to unblock the port. But this does not work as an inno-setup [run] command (because the local machine usually disables scripts from running). (i.e powershell.exe -nowait & script.ps1)
Is there some registry keys in the target machine that I can set that will unblock the port? That I can do pretty easily in inno-setup since the setup.exe runs as an admin. I guess a self-contained EXE could do the same thing.
Here is the script that I would like to replace with just setting the registry settings in HKLM.
set-alias netsh c:\Windows\System32\netsh.exe
$PORT = 4326
$domain = $Env:userdomain
$name = $Env:username
$ErrorActionPreference = "Continue";
netsh http delete urlacl url=http://*:$PORT/
netsh http add urlacl url=http://*:$PORT/ user=$domain\$name
i think you can find firewall rules in HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\
suggestion :
maybe you can just export this key as .reg and import it on the other station .
Instead of using netsh, use the WinApi HttpSetServiceConfiguration instead. You can call this (and its related functions) directly from Inno's [Code] (specifically, in CurStepChanged(ssPostInstall)), given the correct prototype declaration. See the Using DLLs topic in the help file.
See running netsh.exe as a post-install in inno-setup for a continuation of this question. But I basically, jachguate's answer of running netsh.exe as a post install seems the right way to go.