PowerShell script to remove direct IP local printers

Below is PowerShell script which will remove all local printers which are direct IP connected (locally created printer pointed to some network printer). It will not remove standard local printers (like PDF writer, XPS writer, Fax) and also it will not remove queues connected from print server. Not so nice as from PowerShell guru, but can be helpful 🙂

$script:LogFile = "c:\Log\PrinterDirectIPRemove.log"
$script:Version = "1.0.0"

function Get-ScriptName()
{
	$tmp = $MyInvocation.ScriptName.Substring($MyInvocation.ScriptName.LastIndexOf('\') + 1)
	$tmp.Substring(0, $tmp.Length - 4)
}

function Write-Log($Msg, [System.Boolean]$display = $true, $foregroundColor = '')
{
	$date = Get-Date -format MM/dd/yyyy
	$time = Get-Date -format HH:mm:ss
	Add-Content -Path $LogFile -Value ($date + " " + $time + "   " + $Msg)
	if ($display)
	{
		if ($foregroundColor -eq '')
		{ Write-Host "$date $time   $Msg" }
		else
		{ Write-Host "$date $time   $Msg" -ForegroundColor $foregroundColor }
	}
}

function Initialize-LogFile([System.Boolean]$reset = $false)
{
	try
	{
		#Check if file exists
		if (Test-Path -Path $LogFile)
		{
			#Check if file should be reset
			if ($reset)
			{
				Clear-Content $LogFile -ErrorAction SilentlyContinue
			}
		}
		else
		{
			#Check if file is a local file
			if ($LogFile.Substring(1, 1) -eq ':')
			{
				#Check if drive exists
				$driveInfo = [System.IO.DriveInfo]($LogFile)
				if ($driveInfo.IsReady -eq $false)
				{
					Write-Log -Msg ($driveInfo.Name + " not ready.")
				}
				
				#Create folder structure if necessary
				$Dir = [System.IO.Path]::GetDirectoryName($LogFile)
				if (([System.IO.Directory]::Exists($Dir)) -eq $false)
				{
					$objDir = [System.IO.Directory]::CreateDirectory($Dir)
					Write-Log -Msg ($Dir + " created.")
				}
			}
		}
		#Write header
		Write-Log "************************************************************"
		Write-Log "   Version $Version"
		Write-Log "************************************************************"
	}
	catch
	{
		Write-Log $_
	}
}

function Test-IsAdmin
{
	
	([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
	
}

# MAIN SCRIPT PART
Initialize-LogFile
if (!(Test-IsAdmin))
{
	Write-Log "Please run this script with admin priviliges"
	exit
}

[array]$printers = Get-WmiObject "Win32_Printer" | Where-Object { $_.Network -eq $false }
[array]$ports = Get-WmiObject "Win32_TCPIPPrinterPort" | Where-Object { $_.PortNumber -eq 9100 }
[array]$printersToDelete = $printers | Where-Object { $_.PortName -in $ports.Name }
Write-Log "Found $($printers.Count) local printers, and $($ports.Count) TCP/IP printer ports. Found $($printersToDelete.Count) direct IP printers to delete..."
foreach ($printer in $printersToDelete)
{
	Write-Log "Deleting printer with name - $($printer.Name)..."
	try
	{
		$port = $printer.PortName
		$printer.Delete()
		Write-Log "`tsuccessfully deleted printer with name - $($printer.Name), going to delete printer port $($port)..."
		try
		{
			$portToDelete = $ports | Where-Object { $_.Name -eq $port }
			$portToDelete.Delete()
			Write-Log "`tprinter port $($port) deleted."
		}
		catch
		{
			Write-Log "`t!!!problem during deleting printer port $($port) - error:$($_)"
		}
	}
	catch
	{
		Write-Log "`t!!!problem during deleting printer $($printer.Name) - error:$($_)"
	}
}
Write-Log "End of script..."

# END OF MAIN SCRIPT PART
Advertisements

Windows 10 Start menu not working

I had a problem with Start menu on Windows 10 not displaying. I have tried tens of procedures available on the Internet which include Powershell Appx re-registration, new user creation, booting system in safe mode, but nothing helped me.

I realized that issue was in missing permissions to HKEY_CLASSES_ROOT hive. So here is the procedure how I fixed it:

  1. open regedit
  2. find HKEY_CLASSES_ROOT hive, right-click and select Permissions
  3. add (if not added already) – CREATOR OWNER & ALL APPLICATION PACKAGES groups
  4. for CREATOR OWNER – set Full control permission, for ALL APPLICATION PACKAGES – set Read permission
  5. I am not now sure if I had to reboot or not, but if it will not start working immediately, just reboot
  6. If this procedure helped you, leave a comment so I will know that it is working for somebody else than me 🙂

SqlException: Incorrect syntax near ‘OFFSET’.

If you are developing MVC application with Entity Framework using localDB database on your developer machine and then you put your product to the production server with older version of SQL Sever (2008R2 in my case) you can get exception below:

SqlException (0x80131904): Incorrect syntax near 'OFFSET'. 
Invalid usage of the option NEXT in the FETCH statement. 
Incorrect syntax near 'OFFSET'.

The issue is caused by the fact that SQL Server 2008 R2 doesn’t support SQL command OFFSET which can be called by Entity Framework.

To fix this behavior, you need to open your model .EDMX file in some XML editor and edit ProviderManifestToken from version 2012 to version 2008. Compile and it will be working again 🙂

<Schema Namespace="ComplianceRiskModel.Store" ProviderManifestToken="2012" Provider="System.Data.SqlClient" ...>

Enter-PSSession : Connecting to remote server failed…

A while ago I came across an interesting problem I’d like to share with you. Running Enter-PSSession command from one particular terminal server always failed with following error message:
Enter-PSSession_01
To make the matters worse, that terminal server was our management server, that is the single server that is used to manage a few thousand workstations. I was pretty sure that the remote host client2 was reachable, and configured correctly, because I was able to connect to it from other servers using the same command. But still this single terminal server refused to connect to the client. I tried everything I could come up with or find on the Internet, but to no avail. I was determined to fix this, so I waited for the night hours to have management server free of users and I sniffed the network communication while running the Enter-PSSession repeatedly. In the network sniff I saw a very strange DNS queries for some host “proxy-server” which did not exist in our network.
Enter-PSSession_02
Finally I got some lead and I started to Google for description of how PowerShell uses proxy server configuration. I found out that it is using proxy setting configured for the “SYSTEM” account. I checked the proxy configuration for that account and I found out that my colleague has accidentally configured a non existing proxy server on this management server.
Enter-PSSession_03
I changed the settings back to “none” proxy server using the netsh native command.
Enter-PSSession_04
Running the Enter-PSSession command again I immediately saw that the server was able to reach “client2” and that the communication was successfully started:
Enter-PSSession_05
Enter-PSSession_06
In the screenshot you can see a Kerberos ticket request for client2, followed by DNS query for client2 and finally HTTP communication for the Enter-PSSession command.

This also meant that I was finally able to enter a PSSession and the problem was fixed.

Mikrotik – WiFi roaming with multiple routers/APs

I love Mikrotik network devices – I have two of them at home. One which covers 1st floor with WiFi signal and second which covers ground floor and my garden. I have different SSIDs on them, because when I had identical SSIDs it was not working very well.

My friend told me last month about Mikrotik quite new function called CAPsMAN which is doing automatic configuration of APs on all your Mikrotik devices and offers also roaming functionality. Recommended minimal firmware is 6.28 and you need to install Mikrotik package wireless-cm2.

I got it working, but I am still struggling with lower performance (50%) of WiFi when roaming is enabled. Once I solve this problem I will publish also howto for configuration.

How to quickly increase user experience on your virtual desktop

Have you deployed virtual desktop and your users start to complain about slow window moving/minimizing/maximizing on Windows 8.1? Here is a quick procedure how to increase their user experience immediately until you will test and implement 20 pages optimization guide obtained from you VDI vendor 🙂

Navigate to Control Panel – Ease of Access – Optimize visual display and check the “Turn off all unnecessary animations” setting.

Animations_off

Don’t forget to have at least one authoritative DHCP server in network

I would like to describe potential issues with network connection in your network if you will not have authoritative DHCP server in your network. Authoritative DHCP server is a server which always respond to DHCP request if no another DHCP server in network responds.

Imagine situation when you are providing to your laptops to their WiFi adapters IP addresses via DHCP with lease time 7 days. Your user will hibernate or turn off the computer and will come home where he don’t have their home router DHCP configured as authoritative (not usual for home routers, but it can happen in some hotels). Behavior of Windows without enabled APIPA is that this computer resumed/started at home will try to keep it’s IP address which has assigned from work DHCP server and is still valid (lease time 7 days). Normally it will not try to get new IP address and this will result that this computer will have no connectivity. Possible solution to this situation is to enable APIPA (automatic private IP addressing) where computer will assign self-generated IP and simultaneously will start new clean DHCP request.

Explanation how DHCP process works

1. Assign of new IP address

Process of assigning new IP address to client computer
Process of assigning new IP address to client computer
  1. DHCP DISCOVERY – client will send a DHCP DISCOVERY packet to destination address 255.255.255.255 (source address 0.0.0.0) which is trying to find DHCP server in the network and ask for an IP address. The request contains also MAC address of the client which is requesting the address. Address 255.255.255.255 is broadcast address and means that the packet is possibly intended for any other host in the network.
  2. DHCP OFFER – DHCP server will send the DHCP OFFER packet which contains offered IP address (and also other information like netmask, gateway, lease time, etc). Packet is sent to destination address 255.255.255.255 (source address is IP of DHCP server).
  3. DHCP REQUEST – client will send to the address 255.255.255.255 request with IP address which has DHCP server offered in DHCP OFFER.
  4. DHCP ACK – DHCP server will confirm assignment of IP address to the client.
  5. DHCP INFORM – client will inform all clients in the network (broadcast) that it has assigned the specified IP address.
Network sniff of the process
Network sniff of the process

2. Confirmation of address validity after computer was switched off

Process of renew non expired IP address
Process of renew non expired IP address
  1. DHCP REQUEST – After power on of the computer if it has valid (not-expired) IP address it will try to use it and will send the DHCP REQUEST with specified IP address to broadcast address 255.255.255.255.
  2. DHCP ACK – DHCP server will confirm assignment of IP address to the client.
Network sniff of the process
Network sniff of the process

Windows system behavior

1. Wakeup of computer in “new” zone without authoritative DHCP server, IP address non-expired

dhcp_2_1_sniff

User has after switch off moved to the hotel or to another branch, assigned IP address is non-expired. When he will turn on the computer in the new locality, computer is whole time trying to get his old (still valid) IP address. If in the network is no authoritative DHCP server present, all DHCP servers will ignore the request (it is not renewal request for the IP address which he has provided) and client will get into unstable state where it is infinitely requesting the IP address which it cannot get.

This is problematic situation causing troubles to user.

2. Wakeup of computer in “new” zone with authoritative DHCP server, IP address non-expired

dhcp_2_2_sniff

User has after switch off moved to the hotel, assigned IP address is non-expired. When he will turn on the computer in the new locality, computer is trying to get his old (still valid) IP address. If in the network is authoritative DHCP server it will respond with DHCP NAK message (refuse of use wanted IP address) which will cause client will throw away old IP and will start whole DISCOVERY process to obtain new IP address. As you can see user will get new IP address automatically in 3 seconds.

This is correct situation causing no troubles to user.

3. Wakeup of computer in “new” zone, IP address expired

dhcp_2_3_sniff

User has after switch off moved to the hotel, assigned IP address has expired during computer was off. When he will turn on the computer in the new locality computer knows that IP address has expired and will start whole DISCOVERY process to obtain new IP address. As you can see user will get new IP address automatically in 3 seconds.

This is correct situation causing no troubles to user.

4. Wakeup of computer in “new” zone without authoritative DHCP server, IP address non-expired, APIPA enabled

dhcp_2_4_sniff

On the network sniff you can see the same problematic situation as described above, but if APIPA is enabled, computer will in 30 seconds detect that it is in unstable state, it will assign itself APIPA address and will start whole DISCOVERY process to obtain new IP address.

APIPA (Automatic Private IP Addressing) is a built-in Windows feature which will assign to computer automatic private IP address from special reserved network subnet 169.254.0.0-169.254.255.255 when no DHCP server is available on the network. This is possibly to use at home or in small networks where administrator don’t need to care about assignment of IP addresses and all clients will configure itself automatically. In our big corporate network is not important the part that computer will configure automatic private IP address, because our network infrastructure will not route clients with private address.

For our issue is interesting feature that when computer will assign itself APIPA address it will also start to do the DHCP DISCOVERY process in regular intervals until it will get the address from DHCP.

APIPA is in Windows by default enabled.

This is problematic situation but it will be solved automatically in 30 seconds. During connecting to WiFi user will get the message “connecting takes longer than usual”…