Scripting

Automating Web URLs as Start Menu Links

Posted on Updated on

In my previous post on Creating Web URLs as Start Menu Links, I outlined details how to manually create links to URLs (as seen in the images below).  While this does work, most folks in the systems management community would prefer to automate this link creations.  The following PowerShell script can be used to create a custom start menu link for all users.

Note that a problem that you may encounter is the link not being displayed in the grouping.  This could be caused by having two .lnk files with the same target path pointing to the same URL.


# Create a Shortcut with Windows PowerShell
$oWScriptShell = New-Object -ComObject WScript.Shell
$sTargetFile = "C:\Windows\explorer.exe"
$sShortcutFile = $oWScriptShell.SpecialFolders("AllUsersPrograms") + "\Links\t3chn1ck.lnk"
# Note: to open URL in a specific browser like Edge, add in front of the URL Microsoft-edge:
$sURL = "http://t3chn1ck.com"

#Delete existing shortcut if exists
If (Test-Path $sShortcutFile){
Remove-Item $sShortcutFile
}

$oShortcut = $oWScriptShell.CreateShortcut($sShortcutFile)
$oShortcut.IconLocation = "explorer.exe,20"
$oShortcut.TargetPath = $sTargetFile
$oShortcut.Arguments = $sURL
$oShortcut.Save()

urldemo5 urldemo4

Azure AD – PowerShell Script to Change UPN of All Users in a Group

Posted on Updated on

Imagine that if users in a domain have a UPN suffix which is not a public domain, such as @company.local instead of @company.com.  When those users synchronize into Azure AD for EMS, Intune, O365, etc., then the users’ UPNs will be @company.onmicrosoft.com instead of a friendly @company.com UPN for logging into portals or for enrolling devices.

This is an instance that recently occurred for a customer.  There are plenty of PowerShell examples around for how to change the UPN of users in Azure AD.  However, this customer wanted the ability to only change the users that were part of a specific AD group, rather than the entire organization.

The following PowerShell script can do exactly just that.  But please use extreme caution and thoroughly test the script first as well as the impact to those users and the Microsoft cloud technologies which they use.  There are high risks and many possible negative side effects.  Use this script at your own risk.


# This script will change the UPN for the user members of an AD group
$AdGrp = "EMS_Users"
$oldSuffix = "@company.onmicrosoft.com"
$newSuffix = "@company.com"

# Get the AD Group in Azure
$AzAdGrp = Get-MsolGroup -All | Where-Object { $_.DisplayName -eq $AdGrp }
$AzAdGrp_members = Get-MsolGroupMember -All -GroupObjectId $AzAdGrp.ObjectId
write-host "Total members of group: " $AzAdGrp_members.Count

# Create array of users to change
# Example command to test only a portion of the users in the group:
$users = Get-MsolGroupMember -All -GroupObjectId $AzAdGrp.ObjectId | Get-MsolUser | Where-Object { $_.UserPrincipalName -like "*john.doe*"}
# Command to run for all users in the group:
# $users = Get-MsolGroupMember -All -GroupObjectId $AzAdGrp.ObjectId | Get-MsolUser

# Change UPN of users
$users | ForEach-Object {
    $newUpn = $_.UserPrincipalName.Replace($oldSuffix,$newSuffix)
    Set-MsolUserPrincipalName -NewUserPrincipalName $newUpn -UserPrincipalName $_.UserPrincipalName
    Write-host "New UPN assigned: " $newUpn
}

 

Script to delete any Drive:\smspkg\*.pck files of the specified file age

Posted on Updated on

There are many scripts and examples out there for cleaning up PCK files.  The below script is my rendition to cleanup PCK files that are older than the specified number of days.  This script can be executed via a package in ConfigMgr on systems that are a DP.  Oh and I added some basic logging to the script as well :-)


' Script to delete any Drive:\smspkg\*.pck files of the specified file age
sLogFile = "c:\windows\temp\dp_pck_cleanup.log"
iFileAge = 365

Set oFSO = CreateObject ("Scripting.FileSystemObject") 
Set oOutputFile = oFSO.OpenTextFile (sLogFile, 8, True) 
Set oWMI = GetObject("winmgmts:\\.") 
Set colItems = oWMI.ExecQuery("SELECT * FROM Win32_LogicalDisk") 

oOutputFile.WriteLine "******** PCK cleanup began ********  " & Date

For Each oDrive in colItems 
	sDrive=left(oDrive.caption,1) 
	'wscript.echo "sDrive: " & sDrive
	If (oFSO.FolderExists(sDrive & ":\smspkg\")) Then    
		oOutputFile.WriteLine "Smspkg exists on drive " & sDrive
		Set receive = oFSO.GetFolder(sDrive & ":\smspkg\") 
		Set colFiles = receive.Files 
		
		For Each oFile in colFiles 
			sFileName=(lcase(oFile))
			'wscript.echo sFileName
			If (right(sFileName, 4) = ".pck") then 
				'wscript.echo "This is a PCK file"
				If DateDiff("d", oFile.DateLastModified, Date) > iFileAge Then 
					oOutputFile.WriteLine oFile & " exists with modified date: " & oFile.DateLastModified & ", Size (MB):" & vbtab & int(oFile.Size/1048576) 
					oFSO.DeleteFile oFile,TRUE 
					oOutputFile.WriteLine "      Deleted successfully "
				End If 
			End If 
		Next 
	Else
		oOutputFile.WriteLine "No smspkg folder on " & sDrive
	End If 
Next 

Script to delete specific IE cookies

Posted on Updated on

An old script to share :-) It will delete IE cookies specified in variable CookieName

'==========================================================================
' NAME: DeleteIeCookiesCraigslist
' AUTHOR: Nick Moseley , https://t3chn1ck.wordpress.com
' DATE  : 8/11/2011
'
' COMMENT: Deletes the cookies specified in variable CookieName
'==========================================================================
Option Explicit

Const CookieName = "EnterCookieName"
Const ForAppending = 8
Const HKLM = &H80000002
Const EnableLogging = True

' Basic objects
Dim oReg, oShell, oFSO, iCountFiles
Set oReg = GetObject("winmgmts:\\.\root\default:StdRegProv")
Set oShell = CreateObject("WScript.Shell")
Set oFSO = CreateObject ("Scripting.FileSystemObject")
iCountFiles = 0

'==========================================================================
' Begin log file etnries
'==========================================================================
If EnableLogging = True Then 
	Dim oVersionLog
	If Not oFSO.FileExists("C:\Windows\Temp\DeleteIeCookies.log") Then
		oFSO.CreateTextFile "C:\Windows\Temp\DeleteIeCookies.log"
	End If
	Set oVersionLog = oFSO.OpenTextFile ("C:\Windows\Temp\DeleteIeCookies.log", ForAppending, True)
	
	oVersionLog.WriteLine "Delete Craigslist cookies"
	oVersionLog.WriteLine "  => Began at " & Date & " " & Time
End If
'==========================================================================

' Get list of folders in C:\Users
Dim oUserFolders, oFolder, colFiles, oUserCookieFolder, oFile
Set oUserFolders = oFSO.GetFolder("C:\Users") 

For Each oFolder In oUserFolders.subfolders 
	DeleteFile ("C:\Users\" & oFolder.name & "\AppData\Roaming\Microsoft\Windows\Cookies") 
	DeleteFile ("C:\Users\" & oFolder.name & "\AppData\Roaming\Microsoft\Windows\Cookies\Low") 
Next 

' End logging
If EnableLogging = True Then 
	oVersionLog.WriteLine "  => Total number of deleted cookies: " & iCountFiles
	oVersionLog.WriteLine "  => Completed at " & Date & " " & Time
	oVersionLog.Close
End If

WScript.Quit

Sub DeleteFile (sFolderPath)
	If oFSO.FolderExists (sFolderPath) Then
		Set oUserCookieFolder = oFSO.GetFolder(sFolderPath)
		Set colFiles = oUserCookieFolder.Files
		For Each oFile In colFiles
			If InStr (oFile.Name, CookieName) Then 
				If EnableLogging = True Then
					oVersionLog.WriteLine "  => Deleted " & sFolderPath & "\" & oFile.Name
				Else
					WScript.Echo sFolderPath & "\" & oFile.Name
				End If
				oFSO.DeleteFile sFolderPath & "\" & oFile.Name
				iCountFiles = iCountFiles + 1
			End If
		Next 
	End If	
End Sub

Script to reset IE 8 zoom

Posted on Updated on

An old script to share :-)  It will help to fix an old problem that occurred in IE 8, if that’s even still around and in use today ;-)

'==========================================================================
' AUTHOR  : Nick Moseley
' COMMENT : This script will parse all User profiles on the computer, load their
' 	HKCU hive, then set the appropriate registry keys.
' HISTORY : 
'	1.0 (01/01/2009) - Original script
'	1.1 (04/07/2009) - Added code for default user profile
'	1.2 (06/07/2009) - Added code for writing changes to C:\Windows\Version Log.txt
'	2.0 (03/01/2010) - Added support/samples for DWORD values. Added custom
'		error codes to check for failed regkey or value creations. Added
'		a skip for svcdesktopauthclient account.
'	2.1 (05/04/2011) - FIxed the logging to not use asterisks
'==========================================================================
Option Explicit

Const ForAppending = 8
Const HKLM = &H80000002
Const sUserKey = "\Software\Microsoft\Internet Explorer\Zoom" ' Note: key must have a leading backslash
Const sDWORDValueName = "ResetZoomOnStartup2"
Const sDWORDValue = "1"

Dim oReg, oFSO, oFile, oUserSubkey, aUserProfiles, oShell
Dim sProfileLCase, sRegExe, sRegLoad, sRegUnload, sHiveName, sSubPath, sProfile, sValueName, sKeyPathUserProfiles, sValue, ReturnVal

Set oReg = GetObject("winmgmts:\\.\root\default:StdRegProv")
Set oShell = CreateObject("WScript.Shell")
Set oFSO = CreateObject ("Scripting.FileSystemObject")

'==========================================================================
' Begin log file etnries
'==========================================================================
If Not oFSO.FileExists("C:\Windows\Temp\ResetIe8zoom.log") Then
	oFSO.CreateTextFile "C:\Windows\Temp\ResetIe8zoom.log"
End If
Set oFile = oFSO.OpenTextFile ("C:\Windows\Temp\ResetIe8zoom.log", ForAppending, True)

oFile.WriteLine "Configuration of user settings for IE 8 Reset Zoom Level"
oFile.WriteLine "  => Began at " & Date & " " & Time
oFile.WriteLine "  => For each user profile, set " & sDWORDValueName & " (string) to " & sDWORDValue & " in HKCU" & sUserKey
'==========================================================================


' Begin configuration of existing user profiles
sValueName = "ProfileImagePath"
sKeyPathUserProfiles = "SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList"
sRegExe = "C:\Windows\system32\reg.exe"

oReg.EnumKey HKLM, sKeyPathUserProfiles, aUserProfiles

' Existing User Profiles
For Each oUserSubkey In aUserProfiles
    sSubPath = sKeyPathUserProfiles & "\" & oUserSubkey
    oReg.GetExpandedStringValue HKLM,sSubPath,sValueName,sValue
  
    sProfile = Split(sValue, "\")
    sProfileLCase = LCase(sProfile(2))
  
    If sProfileLCase = "system32" Then
    	oFile.WriteLine "  => Skipped user profile: system32"
    ElseIf sProfileLCase = "localservice" Then
    	oFile.WriteLine "  => Skipped user profile: localservice"
    ElseIf sProfileLCase = "networkservice" Then
    	oFile.WriteLine "  => Skipped user profile: networkservice"
    ElseIf sProfileLCase = "serviceprofiles" Then
    	oFile.WriteLine "  => Skipped user profile: serviceprofiles"
    ElseIf sProfileLCase = "svcdesktopauthclient" Then
    	oFile.WriteLine "  => Skipped user profile: svcdesktopauthclient"
    Else
    	sHiveName = "TempHive_" & sProfileLCase
    
    	' Load user's profile hive into a temp location
    	sRegLoad = " LOAD HKLM\" & sHiveName & " """ & sValue & "\ntuser.dat"""
    	oShell.Run sRegExe & sRegLoad, 0, True
    
    	' Call subroutine to change registry key
    	SetConfigUserHive (sHiveName)
		oFile.WriteLine "  => Set user profile: " & sProfileLCase
    
    	' Unload user's profile hive
    	sRegUnload = " UNLOAD HKLM\" & sHiveName
    	oShell.Run sRegExe & sRegUnload, 0, True
    End If  
Next

' Default User Profile
sHiveName = "TempHive_DefaultUser"
sRegLoad = " LOAD HKLM\" & sHiveName & " ""C:\Users\Default\ntuser.dat"""
oShell.Run sRegExe & sRegLoad, 0, True
SetConfigUserHive (sHiveName)
oFile.WriteLine "  => Set user profile: Default User"
sRegUnload = " UNLOAD HKLM\" & sHiveName
oShell.Run sRegExe & sRegUnload, 0, True

' End logging
oFile.WriteLine "  => Completed at " & Date & " " & Time
WScript.Quit (oFile.Close)

Sub SetConfigUserHive (sTempHive)
	Dim sTempHiveKeyPath

	' Path of registry keys
	sTempHiveKeyPath = sTempHive & sUserKey

	' Create registry key if the value doesn't already exist
	If oReg.GetDWORDValue(HKLM, sTempHiveKeyPath & "\", sDWORDValueName) <> 0 Then
		ReturnVal = oReg.CreateKey(HKLM, sTempHiveKeyPath)
	End If

	' Create DWORD Value
	ReturnVal = oReg.SetDWORDValue(HKLM, sTempHiveKeyPath & "\", sDWORDValueName, sDWORDValue)
End Sub



Script to disable NIC power save features

Posted on Updated on

An old script to share :-)  It will parse the list of available network adapters to then disable power save features.

'==========================================================================
' NAME: SetNetworkPnPCapabilities
' AUTHOR: Nick Moseley , https://t3chn1ck.wordpress.com
' COMMENT: Parses list of available network adapters to then disable power
'	save features.  For more info, see Microsoft KB837058
' VERSION HISTORY:
'	1.0 (05/09/2011) - Initial script
'	1.1 (05/10/2011) - Fixed logical bug within the If statement for Wan/Lan
'	2.0 (05/10/2011) - Added logging into registry for future inventory
'	3.0 (08/17/2011) - Commented out changes to disable NIC power save as
'		this needs to be enabled in order to support WOL
'==========================================================================
Option Explicit
Const ForAppending = 8

Dim oShell, oWMI, colNetworkAdapterItems, sNetworkAdapterReg
Set oShell = CreateObject ("WScript.Shell")
Set oWMI = GetObject("winmgmts:\\.\root\cimv2")
Set colNetworkAdapterItems = oWMI.ExecQuery ("Select * from Win32_NetworkAdapter")
sNetworkAdapterReg = "HKLM\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002bE10318}\"

' Logging
Dim oFSO, oVersionLog
Set oFSO = CreateObject ("Scripting.FileSystemObject")
Set oVersionLog = oFSO.OpenTextFile ("C:\Windows\Temp\SetNetworkPnPCapabilities.log", ForAppending, True)
oVersionLog.WriteLine "Configuration of Network Adapters"
oVersionLog.WriteLine "  => Started (" & Date & " " & Time & ")"

' Get all objects and take action on network adapters
Dim oItem, sIndexValue, sLomValue
For Each oItem In colNetworkAdapterItems
	If InStr(lcase(oItem.Name),"wan miniport")=0 _
	  And InStr(LCase(oItem.Name),"microsoft isatap")=0 _ 
	  And Trim(oItem.Name)<>"RAS Async Adapter" _
	  And InStr(LCase(oItem.Name),"cisco")=0 Then 
		If oItem.Index < 10 Then
			sIndexValue = "000" & oItem.Index
		Else
			sIndexValue = "00" & oItem.Index
		End If
		
		' ****************************************
		' IMPORTANT: NIC power save as needs to be enabled in order to support WOL
		' Configure/disable Power save on NIC
		'oShell.RegWrite sNetworkAdapterReg & sIndexValue & "\PnPCapabilities", "56", "REG_DWORD"
		'oVersionLog.WriteLine "  => Disabled network adapter power save on device """ & oItem.Name & """"
		'oVersionLog.WriteLine "     Set PnPCapabilities (dword) to 38 in " & sNetworkAdapterReg & sIndexValue
		' ****************************************
				
		' Configure/enable WAN/LAN switching
		sLomValue = ReadRegistryKey (sNetworkAdapterReg & sIndexValue, "LOM")
		If sLomValue<>"1"  And sLomValue<>"null" Then
			oShell.RegWrite sNetworkAdapterReg & sIndexValue & "\LOM", "1", "REG_SZ"
			oVersionLog.WriteLine "  => Enabled WAN/LAN switching on device """ & oItem.Name & """"
			oVersionLog.WriteLine "     Set LOM (string) to ""1"" in " & sNetworkAdapterReg & sIndexValue
		End If		
	End If 
Next 

' End
oVersionLog.WriteLine "  => Completed (" & Date & " " & Time & ")"
WScript.Quit (oVersionLog.Close)

Function ReadRegistryKey (sReadKey, sReadValue)
	On Error Resume Next
	Dim sGetValue
	sGetValue = oShell.RegRead (sReadKey & "\" & sReadValue)
	
	If Err.Number <> 0 Then
		ReadRegistryKey = "null"
	Else
		ReadRegistryKey = cstr(sGetValue)
	End If 	
End Function

Script to Disable WiFi Device

Posted on Updated on

An old script to share :-) Below is an example script that was once used to disable WiFi devices on desktop computers attached to the LAN, but that came with a built-in and enabled WiFi device.


'==========================================================================
' NAME: DisableWifi
' AUTHOR: Nick Moseley, Archstone
' COMMENT: Determines if a network adapter device is wireless/wifi and then
' executes a devcon command to disable the device. This should only target
' Vostro desktops where there is wireless adapter
' VERSION HISTORY:
' 1.0 (05/13/2011) - Initial Script
' 2.0 (05/25/2011) - Added logging into registry for future inventory
'==========================================================================
Option Explicit
Const ForAppending = 8

Dim oWMI, oShell, colItems, oFSO, oFile
Set oShell = CreateObject ("WScript.Shell")
Set oWMI = GetObject ("winmgmts:\\.\root\cimv2")
Set colItems = oWMI.ExecQuery ("Select * from Win32_PnPEntity where name like '%wireless%' or name like '%wifi %'")

'Start logging
Set oFSO = CreateObject("Scripting.fileSystemObject")
Set oFile = oFSO.OpenTextFile ("C:\Windows\Temp\DisableWifi.log", ForAppending, True)
oFile.WriteLine "Disable wireless network adapter"
oFile.WriteLine "  => Started (" & Date & " " & Time & ")"

' If count=0 of the collection, then no wireless devices found
If colItems.count=0 Then
oFile.WriteLine "  => WARNING: Wireless network adapter not found!"
Else
Dim oItem, sDeviceType
oFSO.CopyFile oFSO.GetFile(Wscript.ScriptFullName).ParentFolder & "\devcon\i386\devcon.exe ", "C:\Windows\Temp\devcon.exe"
' Parse the collection of wireless devices to be disabled
For Each oItem In colItems
sDeviceType = UCase(Left(oItem.DeviceID, 3))
If sDeviceType = "PCI" Then
oShell.Run "C:\Windows\Temp\devcon.exe disable ""@" & oItem.deviceID & ""
oFile.WriteLine "  => Disabled " & oItem.Name
oFile.WriteLine "     Device ID: " & oItem.DeviceID
End If
Next
End If
' End
oFile.WriteLine "  => Completed (" & Date & " " & Time & ")"
WScript.Quit (oFile.Close)