Automatically name Computer using PowerShell get host name and MDT - powershell

My question is if it is possible to obtain the Domain Name of a computer in a Enterprise environment and use it as computer name in a MDT deployment.
I am aware that MDT has an option for setting the computer name here: Right cklick on Deployment Share - Rules
I would love to use the variable $CNAME (Computer Name) which I can successfully obtain using the follwing powershell commands as a variable for “OSDComputerName=“ in the deploymentshare settings.
This ps script gets me the right name:
1 Get IP
$IP=((ipconfig | findstr [0-9].\.)[0]).Split()[-1]
2 Do NSLOOKUP of IP
$Lookup=NSLOOKUP $IP
3 Adjust output with regular expressions and -replace modifiers to only contain the real computername without DNS suffix
$regex=$Lookup -match "(^.*\bName\b\:?\s*\b)[\w\d\s\-]*"
$replace1=$regex -replace "Name: "
$CNAME=$replace1 -replace "*DNSSUFFIX*"
Is this possible? Otherwise, can I use the PowerShell Script in any way to rename the computer after the deployment has finished? E.g. which command can I use to use the variable $CNAME as new computer name?

The following Script will use the IP Adress to query your DNS and get the name of the Computer in your Domain and pass it back to MDT as OSDComputerName
This works in an environment where the computers are named like name.xx.yournamespace.de
Add an nslookup.exe from a Windows ISO to your WinPE Boot Image (mount WinPE WIM with DISM and copy nslookup.exe into System32)
Adjust your customsettings.ini Rules, add:
UserExit=Setname.vbs
OSDComputerName=#SetName("%IPAddress%")#
Add a UserExit Script to your Deploymentshare Scripts-Folder, name it Setname.vbs
Function UserExit(sType, sWhen, sDetail, bSkip)
UserExit = Success
End Function
Function SetName(sIP)
Dim rName
Set objShell = createobject("wscript.shell")
strParams = "%comspec% /c nslookup " & sIP & ""
Set objExecObj = objShell.exec(strParams)
Do While Not objExecObj.StdOut.AtEndOfStream
strText = objExecObj.StdOut.Readline()
If instr(strText, "dns-9") Then
strServer = trim(replace(strText,"(null):",""))
Elseif instr (strText, "xx.yournamespace.de") Then
strhost = trim(replace(strText,"(null)",""))
End if
Loop
rName = replace(strhost, ".xx.yournamespace.de", "")
SetName = rName
End Function
Adjust replacements to your Network. SetName will be passed back to MDT.
Hopefully this helps someone!

Related

Convert VBScript Code to Power Shell Code to write the value on the Active Directory computer account description from the windows 10 workstation

I'm trying to write the value on the Active Directory computer account description from the windows 10 workstation.
I success to use this VB Script on startup up group policy on all workstations to write some values (Computer hardware specs) on the Active Directory computer account description.
Set objSysInfo = CreateObject("ADSystemInfo")
Set objUser = GetObject("LDAP://" & objSysInfo.UserName)
Set objComputer = GetObject("LDAP://" & objSysInfo.ComputerName)
objComputer.Description = "Tested PC"
objComputer.SetInfo
is it possible to use Set-ADComputer -Identity computername -Description "Test" from windows 10 workstation without install any module or any other tool.
Best regards
You can use the built-in [ADSI] classes to search AD for the computer object and set attributes:
$filter = "(&(objectCategory=computer)(objectClass=computer)(cn=$env:COMPUTERNAME))"
$computer = [ADSI](([adsisearcher]$filter).FindOne().Path)
$computer.description = $NewDescription
$computer.setinfo()

How to set a static IP address in windows 10?

After searching a code to set a static IP adress using a simple script, I could not find a complete and easy to implement answer on StackOverflow. That led me to the following question:
What would be an "easy^"-to-implement code to set your windows 10 IP adress to a static IP adress, and back to a dynamic IP adress again?
^ Note: Easy is meant as an indicator to ensure the code and its complete implementation is as simple as possible, not that the user could not find it challenging.
Please note that this is the implementation of: http://www.midnightdba.com/Jen/2014/03/configure-static-or-dynamic-ip-and-dns-with-powershell/. All credits go to MidnightDBA. I hope it benefits someone!
To set the IP adress to static manually
Start>control panel>Network and Internet>Network and Sharing Center>Change adapter settings>rmb on the ethernet/wifi/connection that is in use>properties>Select: Internet Protocol Version 4(TCP/IPv4)>Properties>
That should result in the screen similar to the attached image. There you can fill in the numbers manually. These numbers will (probably) be different in your own situation, you need to do the work suggested in note 3. to determine those numbers for yourself.
To set the static IP (semi-automatically):
This means you will be able to to set the IP address to static by opening a file (double clicking a script you've made), and back to a dynamic IP address by running another script you've made. The instruction steps are listed below:
start>type Powershell>rmb>Open powershell as administrator
(Only do this step if you can not immediately run the script the first time.) Type: Set-ExecutionPolicy RemoteSigned -Scope CurrentUser and hit enter, to set the security policy so that you can run a powershell script.
create a .ps1 file named e.g. static_ip.ps1 in for example c:/example_folder with the content:
$wmi = Get-WmiObject win32_networkadapterconfiguration -filter "ipenabled ='true'";
$wmi.EnableStatic("your_static_ip_adress", "your_subnetmask");
$wmi.SetGateways("your_routers_ip_adress", 1);
$wmi.SetDNSServerSearchOrder("your_dns");
OR to set the static IP with just a single double click on the static_ip.ps1 script:
(Note example values filled in)
# 18-07-20 Todo: add wifi network detection that automatically triggers setting a static IP and back dynamic IP.
# First ensure the script is automatically ran as administrator, else it appearently does not have the privileges to change the local IP adress:
$currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
$testadmin = $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
if ($testadmin -eq $false) {
Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
exit $LASTEXITCODE
}
# Next set it static:
$wmi.EnableStatic("192.21.89.5", "255.255.254.0");
$wmi.SetGateways("192.21.89.1", 1);
$wmi.SetDNSServerSearchOrder("192.21.89.1");
# Now close the window this has just created.
# This leaves other Powershell windows open if they were already open before you ran this script.
# Also, It yields an error with a $ sign at the start of the line.
# Source: https://stackoverflow.com/questions/14874619/powershell-exit-doesnt-really-exit
Stop-Process -Id $PID
Then in powershell enter:
cd c:/example_folder
.\static_ip.ps1
Note, if the path to the static_ip.ps1 file contains a space change the change directory-command to:
cd "c:/example_folder"
To make the IP dynamic again (semi-automatically):
Create a text file named for example dynamic_ip.ps1 located e.g. in folder c:/examplefolder with content:
$wmi = Get-WmiObject win32_networkadapterconfiguration -filter "ipenabled ='true'";
$wmi.EnableDHCP();
$wmi.SetDNSServerSearchOrder();
OR to just change it with a single double-click on the dynamic_ip.ps1 script:
#18-07-20 Todo: add wifi network detection that automatically triggers setting a static IP and back dynamic IP.
# First ensure the script is automatically ran as administrator, else it appearently does not have the privileges to change the local IP adress:
$currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
$testadmin = $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
if ($testadmin -eq $false) {
Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
exit $LASTEXITCODE
}
# Next set it dynamic:
$wmi = Get-WmiObject win32_networkadapterconfiguration -filter "ipenabled ='true'";
$wmi.EnableDHCP();
$wmi.SetDNSServerSearchOrder();
# Now close the window this has just created.
# This leaves other Powershell windows open if they were already open before you ran this script.
# Also, It yields an error with a $ sign at the start of the line.
# Source: https://stackoverflow.com/questions/14874619/powershell-exit-doesnt-really-exit
Stop-Process -Id $PID
In powershell:
cd c:/example_folder
.\dynamic_ip.ps1
After you have tried it out the first time in powershell succesfully, you can simply set a static IP adress by opening/running the script by opening it with powershell (In explorer, double click the file, or right mouse button (rmb)>open with powershell). But for this to work, the path to the scripts cannot contain any spaces!
Additional notes:
Do not forget to make the IP adress dynamic again if you leave your home network again, otherwise you can get a problem when you try to access the internet in other wifi/ethernet networks!
your_static_ip_adress: you can read your dynamic ip adress and routers ip adress by: start>type cmd>open command prompt>type: ipconfig, or type: ipconfig -all.* Furthermore, the rules described in the note above, generally apply.
your_routers_ip_adress see "your_static_ip_adress", usually ends with a .1
your_subnetmask see "your_static_ip_adress"
your_dns, this can be your routers ip adress, or for example googles DNS 8.8.8.8.
Rules to determine the static IP adres:
Source:
https://www.howtogeek.com/184310/ask-htg-should-i-be-setting-static-ip-addresses-on-my-router/
3.1 Do not assign an address that ends in .0 or .255 as these addresses are typically reserved for network protocols.
3.2 Do not assign an address to the very start of the IP pool, e.g. 10.0.0.1 as the start address is always reserved for the router. Even if you’ve changed the IP address of your router for security purposes, we’d still suggest against assigning a computer.
3.3 Do not assign an address outside of the total available pool of private IP addresses. This means if your router’s pool is 10.0.0.0 through 10.255.255.255 every IP you assign (keeping in mind the prior two rules) should fall within that range.
This is the (semi) automated equivalent of manually filling in the data of the first figure of this post, in order to set a static IP.
(Wifi connection issues troubleshoot) If:
you have 2 different wifi networks (A and B) to which you can both connect at the same location
where only B has the right "your_routers_ip_adress"/local gateway-adress
And you accidentally set your local IP to (the wrong) static IP whilst connect to the wrong wifi (A),
Then disconnected the wrong wifi (A) before setting the local IP adress to dynamic again,
and (as a consequence) experience wifi troubles: (keeps scanning network requirements).
Then either:
set the local IP adress to dynamic.
Reconnect to the wrong wifi network (A).
Set it back to static, and to dynamic again.
Disconnect from wifi (A).
Now you should be able to connect to both wifi networks correct again.
Or:
set the local IP adress to static.
Reconnect to the wrong wifi network (A).
Set it back to static, and to dynamic again.
Disconnect from wifi (A).
Now you should be able to connect to both wifi networks correct again.
Nice information with GUI and PowerShell.
When you assign the IP manually by the PowerShell, the DNS server IP is important. Also, it can be done via the command prompt which is useful while managing the PCs remotely. The below post has the information. Maybe you can consider adding those steps in your post.
https://tinylaptop.net/how-to-configure-setup-static-ip-on-windows-10-laptop/

Skype for Business in Kiosk Mode

I would like to run Skype for Business in Kiosk mode, therefore I use the same script as he does, but mine doesn't work.
I replaced the following lines:
$Cashier_SID = Get-UsernameSID("bbwallonepeop")
$ShellLauncherClass.SetCustomShell($Cashier_SID, "C:\Program Files (x86)\Microsoft Office\Office16\lync.exe", ($null), ($null), $restart_shell)
but it doesn't start Skype, it doesn't work with any other app either.
When I run the script, the only thing I see when I log on is a black screen, then I can use ctrl+alt+del to start the Taskmanager, then open the explorer and find the powershell exe to run a disabling script.
So there is something happening, the explorer.exe isn't starting anymore (not even for admins, even though it should start for admins) but Skype isn't starting :/
Any ideas? Here the full script:
$COMPUTER = "localhost"
$NAMESPACE = "root\standardcimv2\embedded"
# Create a handle to the class instance so we can call the static methods.
$ShellLauncherClass = [wmiclass]"\\$COMPUTER\${NAMESPACE}:WESL_UserSetting"
# This well-known security identifier (SID) corresponds to the BUILTIN\Administrators group.
$Admins_SID = "S-1-5-32-544"
# Create a function to retrieve the SID for a user account on a machine.
function Get-UsernameSID($AccountName) {
$NTUserObject = New-Object System.Security.Principal.NTAccount($AccountName)
$NTUserSID = $NTUserObject.Translate([System.Security.Principal.SecurityIdentifier])
return $NTUserSID.Value
}
# Get the SID for a user account named "Cashier". Rename "Cashier" to an existing account on your system to test this script.
$Cashier_SID = Get-UsernameSID("bbwallonepeop")
# Define actions to take when the shell program exits.
$restart_shell = 0
$restart_device = 1
$shutdown_device = 2
# Examples. You can change these examples to use the program that you want to use as the shell.
# This example sets the command prompt as the default shell, and restarts the device if the command prompt is closed.
$ShellLauncherClass.SetDefaultShell("cmd.exe", $restart_device)
# Display the default shell to verify that it was added correctly.
$DefaultShellObject = $ShellLauncherClass.GetDefaultShell()
"`nDefault Shell is set to " + $DefaultShellObject.Shell + " and the default action is set to " + $DefaultShellObject.defaultaction
# Set lync/Skype for busniess as the shell for "Cashier", and restart the machine if it is closed.
$ShellLauncherClass.SetCustomShell($Cashier_SID, "C:\Program Files (x86)\Microsoft Office\Office16\lync.exe", ($null), ($null), $restart_shell)
# Set Explorer as the shell for administrators.
$ShellLauncherClass.SetCustomShell($Admins_SID, "explorer.exe")
# View all the custom shells defined.
"`nCurrent settings for custom shells:"
Get-WmiObject -namespace $NAMESPACE -computer $COMPUTER -class WESL_UserSetting | Select Sid, Shell, DefaultAction
# Enable Shell Launcher
$ShellLauncherClass.SetEnabled($TRUE)
$IsShellLauncherEnabled = $ShellLauncherClass.IsEnabled()
"`nEnabled is set to " + $IsShellLauncherEnabled.Enabled
# Remove the new custom shells.
#$ShellLauncherClass.RemoveCustomShell($Admins_SID)
#$ShellLauncherClass.RemoveCustomShell($Cashier_SID)
# Disable Shell Launcher
#$ShellLauncherClass.SetEnabled($FALSE)
#$IsShellLauncherEnabled = $ShellLauncherClass.IsEnabled()
"`nEnabled is set to " + $IsShellLauncherEnabled.Enabled

Creating powershell script to get show on desktop enabled + rename with hostname

I'm just a junior programmer, just started with programming and because my work requests me to create some handy powershell scripts I was wondering if you can help me with a particular one.
We have a lot of customers with a lot of servers. When they are newly installed I do check them and after that we do regular maintenance. Because each customer has several servers with different roles I want to have the "Computer" icon on my desktop.
I can do that by clicking start -> rightclick Computer -> Enable "Show on Desktop"
Furtheron I want to have this Computer icon renamed to the hostname (because the hostname tells me it's role in the domain)
Now my goal is to create a powershell script that creates this computer icon with hostname for all the server in the domain.
I've tried to search my way to the usual search engines and came up with this:
1) Locate with regedit [HKEY_CLASSES_ROOT\CLSID\{20D04FE0-3AEA-1069-A2D8-08002B30309D} rename LocalizedString to LocalizedString.Old
2) Now switch to Regedit32 Create a new VALUE type Expand_SZ name it LocalizedString On XP and Windows 2000 with SP3 replace LocalizedString with %Username% at %Computername%
Which isn't suitable because we use W2K8R2SP1 servers.
After that I ended up with this script:
$ComputerName = "Localhost"
$Hive = "CurrentUser"
$Key = "Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel"
$MyComputer = "{20D04FE0-3AEA-1069-A2D8-08002B30309D}"
$UserFiles = "{59031a47-3f72-44a7-89c5-5595fe6b30ee}"
$Kind = [Microsoft.Win32.RegistryValueKind]
$RegHive = [Microsoft.Win32.RegistryHive]$hive
$RegKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($RegHive,$ComputerName)
$MyComputerValue = ($RegKey.OpenSubKey($Key)).GetValue($MyComputer)
$UserFilesValue = ($RegKey.OpenSubKey($Key)).GetValue($UserFiles)
if ($MyComputerValue -eq $null -or $MyComputerValue -eq 0)
{
$Computer = $regKey.OpenSubKey($RootKey,$true)
$Computer.SetValue($MyComputer, 1,$Kind::DWord)
}
if ($UserFilesValue -eq $null -or $UserFilesValue -eq 0)
{
$User = $regKey.OpenSubKey($RootKey,$true)
$User.SetValue($UserFiles, 1,$Kind::DWord)
}
This doesn't seem to be doing anything at all.
I know this registry key is used for the computer on desktop:
“{20D04FE0-3AEA-1069-A2D8-08002B30309D}”=dword:00000000
Continued search...
So I found this:
To show the ‘My Computer’ icon on the desk"text-decoration:underline;">
[HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\HideDesktopIcons\NewStartPanel]
Name = {20D04FE0-3AEA-1069-A2D8-08002B30309D}
Type =REG_DWORD
Value = 0
To change the ‘My Computer’ icon to computer or user name:
[HKCR\CLSID\{20D04FE0-3AEA-1069-A2D8-08002B30309D}]
Name = LocalizedString
Type = REG_EXPAND_SZ
Data value = %computername% or any combination you like – eg %username% %computername%
However the second part keeps giving me an error and even if i can get it to work, i want to run the script onces and all servers in domain should be having this update.
Thanks for helping out.
Best regards,
Nick
Changing HKCR\CLSID\{20D04FE0-3AEA-1069-A2D8-08002B30309D}\LocalizedString is still suitable on Server 2008 R2, but you need to take ownership of the key and grant administrators full access to it first.

Executing ps script on remote machine with VBscript

I am attempting to execute a powershell script on 10.0.0.20 found at D:\path\script.ps1 with the parameter of 6.9.0 from 10.0.0.199 using VBscript. I believe I am on the right route with the following code but I'm not sure where to go from here. Any suggestions?
side note, it needs to run as administrator
sub main()
dim strComputer, strUser, strPassword
strComputer = "10.0.0.20"
strUser="userName"
strPassword="password"
Set objSWbemLocator = CreateObject("WbemScripting.SWbemLocator")
Set objSWbemServices = objSWbemLocator.ConnectServer (strComputer, "root\cimv2", strUser, strPassword)
objSWbemServices.Security_.ImpersonationLevel = 3
end sub
main
Enable PSRemoting on the remote system and invoke it that way, assuming that your workstation and the remote system are on the same domain, and your domain account has admin access to the remote system.
Invoke-Command -computer "10.0.0.20" -scriptblock {. d:\path\script.ps1}