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" ...>

ASP.NET MVC – SQL Server Compact (SQL Server CE) first load slow

I had a problem with very long first load of my ASP.NET MVC webpage with SQL Server Compact when I deployed it to IIS. In Visual Studio it was working quite OK, but after deploy to IIS load took about 40 seconds.

I browsed Internet without success, but after few days I found this blog which solved my problem! Thank you ErikEj!

I haven’t configured internet proxy for local system account which was needed for CRL checking during load (netsh winhttp set proxy proxyServer:port “<local>”)

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.

Windows machine as a router

ImWindows machine as a routeragine that you have your home network connected with your friend’s network using OpenVPN open source VPN solution. Your friend want to access your media server in your network to see pictures from the party, or access your game server running on your laptop. VPN is connected, but he is not able to reach your computer…

It’s because on your windows machine running OpenVPN server you didn’t enable routing, so windows machine is not acting as a router and all packets end on the OpenVPN server itself without being forwarded to your home network.

To enable routing functionality of your windows machine create in reg key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters value of type REG_DWORD IpEnableRouter =1. After reboot of the system it will act as router and start routing packets according to it’s routing table.

Printing even without toner?

All of us know it… You want to print one page flight ticket in the evening before flight, but your printer tells you, that you don’t have blue toner, so your black&white ticket cannot be printed. 🙂

For HP printers I have found very useful feature, that you can enable “cartridge out override” feature which will cause that you are able to print even when toner is out.

Not all printers support it, but here you can find a list of printers where you can see if it is supported or not for your printer – click here (first half of page contains printers which does not support it, second one is more interesting).

If it is supported for your printer, you need to have installed HP Toolbox (if you used your CD shipped with the printer, you have it). Then go to Device Settings – System Setup – Cartridge out override and set it to ON.

cartridge_out