I'm trying to record and compare my WAN IP address changes.
I found a very useful script (sorry, can't remember the author but thank you!), to save IP in a txt file and I changed it a bit to suit my needs. Now, I'd like to search through txt file each time and add message on screen that IP was never used before or is duplicated.
I am not a programmer and would be grateful for any help.
Script below.
$ipDetectionUrl = "https://wtfismyip.com/text"
$IPAddFile = "C:\IP.txt" #absolute path to file that stores the old IP
record
$Request = Invoke-WebRequest $ipDetectionUrl
$IP_new = ($Request.Content.Trim())
Write-Host "Current IP address: [$IP_new]"
#Check if old IP record exists
If(Test-Path "$IPAddFile")
{
#Get old IP
$IP_old = Get-Content "$IPAddFile" -Tail 1
#Compare IPs
if(-not($IP_new -eq $IP_old))
{
Write-Host "Old IP address: [$IP_old]"
#Overwrite and update new IP
$IP_new | Out-File $IPAddFile -Append
}
else
{"No change"}
}
else
{
#Create new, as file not found
$IP_new | Out-File $IPAddFile
"File created"
}
An If can have multiple elseif with other conditions but only one else
Proper formatting with indents for script blocks renders your code better
readable/understandable also for yourself.
## Q:\Test\2018\11\17\SO_53351417.ps1
$ipDetectionUrl = "http://api.ipify.org"
$IPAddFile = "C:\IP.txt" #absolute path to file that stores the old IP record
$IP_new = (Invoke-WebRequest $ipDetectionUrl).Content.Trim()
Write-Host "Current IP address: [$IP_new]"
#Check if old IP record exists
If(!(Test-Path $IPAddFile)){
#Create new, as file not found
$IP_new | Out-File $IPAddFile -Encoding default
"File {0} created" -f $IPAddFile
}
#Get all old IPs
$IP_old = Get-Content $IPAddFile
# 1st compare last IP, then other IPs
if($IP_new -eq $IP_old[-1]){
"No change"
} else {
if ($IP_old -contains $IP_new) {
$LinesAgo = $IP_old.Length - [array]::IndexOf($IP_old,$IP_new') ######
$wshell = New-Object -ComObject Wscript.Shell
$wshell.Popup($IP_new,0,"IPaddress reused",0x0)|Out-Null
Write-Host "Old IP address reused [$LinesAgo] lines ago: [$IP_new]" #####
} else {
Write-Host "New IP address: [$IP_new]"
}
# Append new (or reused) IP
$IP_new | Out-File $IPAddFile -Append -Encoding default
}
I used http://api.ipify.org because it prefers IPv4 over IPv6 addresses.
Related
i have this script , that take IP Address and ping them , and then it save the result to TXT file or EXCEL file.
and the issue is that - > If i will change the name output name file and even change the IP address from the original ( or new ) file i will get in the end file with all the previous test connections.
The Script :
$IPs = Get-Content "C:\IPs.txt"
foreach($name in $Ips){
if(Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue){
Write-Host "$name is up" -ForegroundColor Green
$output+="$name is up,"+"`n"
}
else{
Write-Host "$name is down" -ForegroundColor Red
$output+="$name is down,"+"`n"
}
}
$output | Out-File "C:\IP_Result"
TXT file with the IP Address :
8.8.8.8
192.168.33.2
10.10.10.10
192.168.33.4
1.1.1.1
so when i run the script for the first time i receive :
8.8.8.8 is up,
192.168.33.2 is up,
10.10.10.10 is down,
192.168.33.4 is up,
1.1.1.1 is up,
now if i will change the $output | Out-File to another file name ( so i can get new file with results )
i will receive new file name but will the previous results
for example
New IP Address ( inserted in new file with new name in $IPs = Get-Content )
2.2.2.2
3.3.3.3
4.4.4.4
now i run the script and the result :
8.8.8.8 is up,
192.168.33.2 is up,
10.10.10.10 is down,
192.168.33.4 is up,
1.1.1.1 is up,
1.1.1.1 is up,
2.2.2.2 is down,
3.3.3.3 is down,
4.4.4.4 is down,
why i see the old results ?
You use the same variable $output and keep appending to it ($output +=). If you ran the script in a completly new window, you would get single results.
To prevent that behavior initiate the variable $output in the beginning of the script:
$output = $null # = empty
or
$output = #() # = array
or
$output = "" # = string
Another way would be to remove the variable when you are done using it:
Remove-Variable output
Here is an additional tipp:
Using += will recreate the collection with every iteration. For a few dozen values thats ok but for multiple hundred it's much faster to collect the output of the foreach itself:
$output = foreach($name in $Ips){
if(Test-Connection -ComputerName $name -Count 1 -ErrorAction SilentlyContinue){
Write-Host "$name is up" -ForegroundColor Green
"$name is up,"
}
else{
Write-Host "$name is down" -ForegroundColor Red
"$name is down,"
}
}
And you wont have to reinitiate the variable by yourself.
In an attempt to reduce the number of DNS lookups occurring against our DNS SPF record I have written a PowerShell script which will extract out all of the allowed IP addresses from a SPF netblock (i.e. _netblocks.eloqua.com) and transforms it into this:
v=spf1
ip4:129.145.16.0/24
ip4:129.145.17.0/24
ip4:129.145.18.0/24
ip4:129.145.20.0/24
ip4:129.145.21.0/24
ip4:129.145.22.0/24
ip4:129.145.23.0/24
ip4:129.91.16.0/24
ip4:129.91.18.0/24
ip4:129.91.19.0/24
ip4:141.145.10.0/24
ip4:141.145.11.0/24
ip4:141.145.12.0/24
ip4:141.146.113.128/25
ip4:142.0.160.0/20
ip4:142.0.168.0/24
ip4:142.0.174.0/24
ip4:204.92.114.0/24
ip4:204.92.19.0/24
ip4:204.92.21.0/25
ip4:204.92.22.0/24
ip4:204.92.26.0/24
-all
I have the values separated on each line to bypass the Windows DNS Manager TXT record character limitations. I also include a single whitespace character after each entry so it recognizes it as one TXT record properly.
I have all of that working. I can successfully write this to a TXT file (with CRLF endings), copy the contents, paste them into Windows DNS Manager on our DNS server and it will work.
But I want to automate it!
And that is where I am getting stuck. When I try to append the value as a string to the DNS TXT record using Set-DnsServerResourceRecord it presents me with the following error:
Newinputobject for resource record has an invalid value. Failed to set the resource record on NHAEXDNS100.nhacentral.com server. Please check extended error for additional details.
I've tried setting it into a Here string, writing it to file then using Get-Content to extract it with -Raw and get it out that way but it continues to give me this error.
I also tried extracting the data from the error to find this "extended error" data but I can't seem to find that extra data anywhere in the error object (you'll see my attempt to do so in my code).
Here is a snippet of the code I am using for reference:
foreach ($flat_record in $flattened_spf_records)
{
$index = [array]::IndexOf($flattened_spf_records, $flat_record)
$current_spf_record = $null
if ($index -gt 0)
{
$flat_record.DNSEntryValue | Out-File ".\$($flat_record.DNSRecordName).txt"
Get-Content ".\$($flat_record.DNSRecordName).txt" | Out-File ".\$($flat_record.DNSRecordName)-Copy.txt" # To change line endings from Unix style to Windows style for proper copying to Windows Server DNS
Remove-Item ".\$($flat_record.DNSRecordName).txt"
$DNSEntryValues = Get-Content ".\$($flat_record.DNSRecordName)-Copy.txt" -Raw
$current_spf_record = (Resolve-DnsName ("$($flat_record.DNSRecordName).$($flat_record.DNSRecordZoneName)") -Type TXT -Server $dns_external_server -ErrorAction SilentlyContinue | Where-Object {$_.Strings -match "spf"} | Select-Object -ExpandProperty Strings) -join "`n"
if ($current_spf_record -ne $DNSEntryValues -and [string]::IsNullOrWhiteSpace($current_spf_record) -eq $false)
{
"Change detected on $($flat_record.DNSRecordName) in Zone $($flat_record.DNSRecordZoneName)."
$old_domain_spf_record = Get-DnsServerResourceRecord -Name $flat_record.DNSRecordName -ComputerName $dns_internal_server -ZoneName $flat_record.DNSRecordZoneName -RRType "Txt" | Where-Object {$_.RecordData.DescriptiveText -match "v=spf1" -and $_.HostName -eq $flat_record.DNSRecordName}
$new_domain_spf_record = $old_domain_spf_record.Clone()
$new_domain_spf_record.RecordData.DescriptiveText = $DNSEntryValues
try
{
Set-DnsServerResourceRecord -NewInputObject $new_domain_spf_record -OldInputObject $old_domain_spf_record -ComputerName $dns_internal_server -ZoneName $flat_record.DNSRecordZoneName
}
catch
{
$err = $_
$err | gm | ForEach-Object {
$name = $_.Name
$err.$name
}
}
}
}
}
I would like to have the SPF string value listed above automatically written into DNS so I can set my script up to run automatically via scheduled task and keep my SPF records up to date by IP address rather than by DNS lookups. Any help would be appreciated!
Use Case
The below script is to be placed in a scheduled task to notify me if my public IP Address changes
The IF match condition is not the correct behaviour
What would be the best way to match if the IP Address changed and output that to host?
Code
$ip = Invoke-RestMethod http://ipinfo.io/json | select -ExpandProperty ip
$date = (get-date).date
$value = "{0} - {1}" -f ($date),($ip)
Add-Content -Value $value -Path "C:\users\Sumeet\Documents\WindowsPowerShell\ip.txt"
$file = Get-Content -Path "C:\users\Sumeet\Documents\WindowsPowerShell\ip.txt"
if ($file | Select-String -Pattern $ip) {
clear-host
write-host "Match found at $_ your public IP interface has changed"
}
File Output
Date - IP
9/06/2018 12:00:00 AM - 121.211.177.20
9/06/2018 12:00:00 AM - 121.211.177.20
Output
I think something similar would be more helpful, as #LotPings suggested. You should update the file only if there is a change and follow up with notification as needed.
Also note, that change of IP can occur at anytime, but your scheduled task will let you know only whenever it is scheduled to run.
$ip = Invoke-RestMethod http://ipinfo.io/json | select -ExpandProperty ip
$date = (get-date).date
$value = "{0} - {1}" -f ($date),($ip)
$file = Get-Content -Path "E:\Code\powershell\myPS\2018\Jun\checkPublicIP\ip.txt"
if ($file | Select-String -Pattern $ip) {
Write-Host "IP is not changed"
}
else {
#Adding current IP to the file
Add-Content -Value $value -Path "E:\Code\powershell\myPS\2018\Jun\checkPublicIP\ip.txt"
#Add more code as needed for notification / email / alert.
}
Handling of data is IMO done easier when using csv files as columns/properties are assigned on import.
Because of my locale which doesn't support the date separator / or tt for AM/PM I had to use a CultureInfo object.
## Q:\Test\2018\06\09\SO_50771712.ps1
$File = "$Env:USERPROFILE\Documents\WindowsPowerShell\ip.csv"
$CIUS = New-Object System.Globalization.CultureInfo("en-US")
$Actual = [PSCustomObject]#{
Date = (get-date).ToString("d/M/yyyy hh:mm:ss tt",$CIUS)
IP = (Invoke-RestMethod http://ipinfo.io/json).ip
}
if (!(Test-Path $File)){'"Date","IP"'|Set-Content $File}
$Last=Import-Csv $File|Sort-Object {[DateTime]$_.Date}|Select-Object -Last 1
If ($Last.ip -ne $Actual.ip){
Write-Host ("Last ip : {0} from: {1}" -f $LAst.IP,$Last.date)
Write-Host ("New ip : {0} from: {1}" -f $Actual.IP,$Actual.date)
Export-Csv $File -InputObject $Actual -Append -NoTypeInformation
}
Sample output:
> Q:\Test\2018\06\09\SO_50771712.ps1
Last ip : 92.123.13.83 from: 9/6/2018 09:19:21 PM
New ip : 92.123.13.84 from: 9/6/2018 09:34:59 PM
> gc $file
"Date","IP"
"9/6/2018 08:51:00 PM","92.123.13.82"
"9/6/2018 09:19:21 PM","92.123.13.83"
"9/6/2018 09:34:59 PM","92.123.13.84"
I am trying to write a script that will remove old queues from users HKLM (will eventually delete from HKCU by mounting ntuser.dat but I am not there yet).
The problem I am having is that I am only iterating through one sid under SOFTWARE\Microsoft\Windows NT\CurrentVersion\Print\Providers\Client Side Rendering Print Provider\ and I get the following error message:
The term 'else' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is corr
ect and try again.
Has anyone ran into this issue before?
#defining my object that will be used throughout the script. Will be used to log everything
$objQueueData=[pscustomobject]#{
computername=""
computerstatus=""
Registrystatus=""
SID=""
Does_It_Have_2003_Queues=""
User_SID_Status=""
user=""
UNC_2003_Queues=""
}
#$QueueDataCollection=[pscustomobject]#{
#queuecollection=$QueueData
#}
#reading the list of workstations
Get-Content "P:\PowerShell\jm\DeletePrintQueues\Workstations.txt" | ForEach-Object{
$strComputerName = $_
#check if the workstation is up
IF (Test-Connection -ComputerName $strComputerName -count 2 -quiet)
{
#$objUser= Get-ChildItem c:\users
#$strUserName=$objUser.Name
$objQueueData.computername=$strComputerName
$objQueueData.computerstatus="Machine is up"
DeleteHklm $strComputerName
}
else
{
#We are here because the computer could not be reached
Write-Host "Machine down" $strComputerName
$objQueueData.computername =$strComputerName
$objQueueData.computerstatus = "Machine Down"
$objQueueData.Registrystatus ="Machine Down"
$objQueueData.SID = "Machine Down"
$objQueueData.Does_It_Have_2003_Queues="Machine Down"
$objQueueData.User_SID_Status="Machine Down"
$objQueueData.user="Machine Down"
$objQueueData.UNC_2003_Queues="Machine Down"
$objQueueData | Export-Csv P:\powershell\jm\results2.csv -NoTypeInformation -Append
}
}
function DeleteHKLM {
param ([string]$computername)
try{
If($strHklm = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey('LocalMachine',$strcomputername ))
{
#executes when it can open HKLM
$objqueuedata.RegistryStatus = "Was able to open the registry"
#set the path of the registry
$PrinterRegKey = 'SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Print\\Providers\\Client Side Rendering Print Provider'
#$PrinterRegKey
$regPrinterRef = $strHklm.OpenSubKey($PrinterRegKey)
#debug
Write-Host "regprinterref is: "$regPrinterRef
}
If($regPrinterRef)
{
#This executes if there are Printers present in the registry
#region Loop thru all child keys. These contain the calculable UNC paths to 2003
$regPrinterRef.GetSubKeyNames() | ForEach-Object{
#debug
Write-Host "The sid is: " $_
#concatinating to get to the connections key
#$PrinterRegKey
$strPrinterpath =$PrinterRegKey+"\\"+ $_ + "\\Printers\\Connections"
#debug
Write-Host "The printer keys for SID are located in: "
$strPrinterPath
if ($strPrinterpath -notlike "*servers*")
{
#this value is the sid
# $_ will give us the sids. Here I am storing the SIDs into strUserSID to use later on
$strUserSID = $_
#debug
# $strUserSID
# The logic below will convert SID to username
#pass the SID to the secrity principal SID being struserSID
$objSID = New-Object System.Security.Principal.SecurityIdentifier("$strUserSID")
#using a try catch to filter out deleted SIDs, otherwise powershell will throw an error saying it is null
Try{
$strUser = $objSID.Translate( [System.Security.Principal.NTAccount]).Value
$objQueueData.User_SID_Status ="Valid SID"
$strUser
}
Catch{
#$strUserID = $objSID.Value
$objQueueData.User_SID_Status ="Invalid SID"
$objQueueData.User = "Invalid SID"
$objQueueData.Does_it_Have_2003_Queues ="Invalid SID"
$objQueueData.UNC_2003_Queues = "Invalid SID"
$objQueueData | Export-Csv P:\powershell\jm\results1.csv -NoTypeInformation -Append
#exit
}
$regPrinterDetails = $Strhklm.OpenSubKey($strPrinterPath)
$regPrinterDetails.GetSubKeyNames() |ForEach-Object{
#looping through each key at the connections level to search for the 2003 print server names
if($_ -like "*sarspprt2*")
{
$objQueueData.Does_It_Have_2003_Queues = "Yes"
#this value is the printer if it exists
# $_ will give us the printers. Here I am storing the printers into strUserPrinters to user later on
$strUserPrinters = $_
Write-Host "struserprinters value is " $_
#$strUserPrinters
$blnHasOldQueues = $true
#The code below is to build the printer UNC to make it more legible
$intPrinterLength= $strUserPrinters.Length
$strPrintServer= $strUserPrinters.Substring(2,10)
#Doing the -13 because we have to limit the length of the substring statement to the length minus the starting poistion of the substring
$strPrinterShareName =$strUserPrinters.Substring(13,$intPrinterLength-13)
$strPrintUNC = "\\"+$strPrintServer+"\"+$strPrinterShareName
$objQueueData.UNC_2003_Queues = $strPrintUNC
$objQueueData.User = $strUser
$objQueueData | Export-Csv P:\powershell\jm\results.csv -NoTypeInformation -Append
$strkeytodelete=$strPrinterPath+"\\"+$_
$strkeytodelete
#delete 2003 Key
Remove-Item -Path '$strkeytodelete' -Recurse
}
elseif($_ -notlike "*sarspprt2*")
{
#Write-host "No 2003 Queues Detected"
#Write-host "no 2003 Queues detected" $strUserSID,$strUser,$strPrintUNC
$objQueueData.User = $strUser
$objQueueData.Does_it_Have_2003_Queues = "No 2003 Queues Detected for this user or vsarspprt* queue"
$objQueueData.UNC_2003_Queues = "No 2003 Queues Detected for this user or vsarspprt* queue"
$objQueueData | Export-Csv P:\powershell\jm\results.csv -NoTypeInformation -Append
}
# Write-Host $strServer $blnHasOldQueues $strUserSID $strUserPrinters
}
}
}
else
{
#Write-Host "No Printers in the Registry"
$objQueueData.computername=""
$objQueueData.computerstatus=""
$objQueueData.Registrystatus=""
$objQueueData.SID=""
$objQueueData.Does_It_Have_2003_Queues=""
$objQueueData.User_SID_Status=""
$objQueueData.user=""
$objQueueData.UNC_2003_Queues=""
}
}
}
catch{
# Write-Host "cant read registry"
$_.Exception.Message
}
}
You have an extra curly brace on line 153. If you move that to after line 165 it should work, although I can't test it right now. I got in the habit of systematically collapsing my if-else statements to ensure that they all match up with eachother.
Printers at my job are in constant flux. Because of this I need a script that can automate the process of adding and deleting printers with little intervention. I have here an example of the code that I am using to perform this task. I'd like to condense this code and add 2 new features, unfortunately my ability to code is few an far between as I am but a humble systems janitor.
New Feature idea's:
If the .vbs files 'Last Modified' date has not been altered since the last time this script was ran, the script immediately stops. A comment outlining a method to override this would be good too.
The log file that shows which servers were created, I'd like to know if they were created -successfully- or if they failed.
If the script comes across an error while adding a network printer, it will immediately skip it, but the log will show that the printer has been added created
<#
.SYNOPSIS
Printer Script
1. Archives the working file if it is greater than or equal to 1 MB
2. Starts logging
3. Removes priners which no longer exist on the print server (because of deletion, moves, etc) in a status of 2
4. Compares the Network printer list to the locally installed Network printers and outputs a list of the printers not installed locally
5. Takes the new printer list, and pings each printer, if ping fails, the printer is removed from the install list
6. Builds new printers
7. Ends logging
8. Performs log file maintenance by archiving and removing old log files
.DESCRIPTION
Date: 04/03/2013
Version: 1
PowerShell Version: 2.0
.INPUTS
Network Printer Script \\ShareDrive\Sharefolder\ShareFile.vbs
.OUTPUTS
Log files
Archive files
Temp text files
ShareFile.txt
pl.txt
Localprinters.txt
NewPrinters.txt
ToDelete.txt
working.txt
.EXAMPLE
C:\scripts\PrinterMaint.ps1
.NOTES
Create the following folders before running this script:
C:\PrinterMaint\
C:\temp\
C:\Scripts\
.LINK
#>
###################
####-VARIABLES-####
###################
# Get computer name
$Server = (gc env:computername)
# Specifies Local Printer Properties to be retrieved
$Props = "Name","PrinterStatus"
$GLOBAL:job1 = ""
# Log file naming convention
$Logfile = "C:\PrinterMaint\"+$(gc env:computername)+".log"
# Archive log naming convention
$archive = "C:\PrinterMaint\Archive_"+(gc env:computername)+"_"+$date2+".log"
# Gets todays date and assigns it to a variable
$date = Get-Date
# temp files and path of text file which holds the names of the printers to be deleted
$DelFile = "C:\temp\ToDelete.txt"
# Creates a formatted date which can be used in a file name
$date2 = Get-Date -format "yyyy-MM-ddTHHmmss"
# Error File
$ErrorFile = "C:\PrinterMaint\Errors.log"
# Handle Errors
$ErrorActionPreference = "silentlycontinue"
# Get computer name
$Server = (gc env:computername)
# Local Printer
$GOBAL:LPrinter = #()
$GLOBAL:ltext = #()
$GLOBAL:FinalPrinters = #()
$GLOBAL:Bad = #()
###################
####-FUNCTIONS-####
###################
Function ServiceShutdown #Shuts down High CPU services while this script runs so as to not interfere
{
Set-Service SAVAdminService -StartupType Disabled
Stop-Service SAVAdminService
Set-Service SavService -StartupType Disabled
Stop-Service SavService
}
Function CycleSpooler
{
Write-Host "Cycling Print Spooler"
Stop-Service spooler
Start-Sleep -seconds 10
Start-Service spooler
Write-Host "Print Spooler Cycle is complete"
}
Function ServiceReenable
{
Set-Service SavService -StartupType Automatic
Start-Service SavService
Set-Service SAVAdminService -StartupType Automatic
Start-Service SAVAdminService
}
Function GetLocalPrinters
{
# Start gathering local printer info
$GLOBAL:job1 = gWmi Win32_Printer -computer $Server -Property $props -AsJob
If ($GLOBAL:job1.State -eq "Running")
{
Cls
Write-Host "The local Printer gather may take several minutes to complete" -ForegroundColor Blue -BackgroundColor Yellow
$i = 0
do {Write-Progress -Activity "Gathering Local Printers..." -status "$i seconds";$i+=5; Start-sleep -seconds 5}
while ($GLOBAL:job1.State -eq "Running")
Write-Progress "Done" "Done" -completed
Else
{Write-Host "Local printer gather has completed" -ForegroundColor Yellow}
}
}
Function ArchiveLog # Archives log files if they are greater than or equal to 1MB
{
# Creates the Variable which will hold the archive log naming convention
if (test-path $Logfile) #If the logfile exists then determine if it needs to be archived
{
# Gets the log file if it is greater than oe equal to 1MB
Get-ChildItem $LogFile -recurse | ? {($_.length/1MB) -ge 1} | % {
# Archives the log File
Move-Item $_.Fullname $archive
}
}
else # If the log file does not exist
{New-Item $Logfile -type File} # Create a new log file
}
Function LogI # Function Called to Write actions to the log file
{
# Accepts the parameter
Param ([string]$logstring)
# new line
"`r`n"
# Logs variable to the log file
$logstring >> $LogFile
}
Function StartLog # Function called to format the beginning of each log file
{
LogI "**********Starting Log**********"
LogI "Log Date: $(Get-Date)"
}
Function EndLog # Function called to format the end of each log file
{
LogI "**********End Log**********"
LogI "Log Date: $(Get-Date)"
}
Function CleanupTMP # Function called to cleanup all temp files created by this script
{
# Cleanup of existing build files
$workingfiles = "C:\temp\ShareFile.txt", "C:\temp\pl.txt", "C:\temp\Localprinters.txt", "C:\temp\NewPrinters.txt", "C:\temp\ToDelete.txt", "C:\temp\working.txt"
foreach ($file in $workingfiles) # Gets each file, deletes it
{
# Determines if the file in the path exists
if (test-path $file)
{
echo Test-Path $file
# If the file does exist, it deletes each one
Remove-Item $file
# Writes the name of the deleted file to the log file
LogI "Deleted File: $date $file"
}
}
}
Function CleanupLogs # Removes Log files older than 14 days old
{
# set folder path
$log_path = "C:\PrinterMaint\Archive*.log"
# set min age of files to 14 days
$max_days = "-14"
# determine how far back we go based on current date
$del_date = $date.AddDays($max_days)
# Gets log files older than the $max_days defiled and Removes them
Get-ChildItem $log_path -Recurse | Where-Object { $_.LastWriteTime -lt $del_date } | Remove-Item
}
Function BadPrinter # Function checks for indtalled printers with a status of 2, "Printer not Found on Server, unable to connect"
{
# Handle Bad Printers
# Gathers Printers with status of 2 - Not Found on Server
$GLOBAL:Bad = $GLOBAL:LPrinters | where {$_.printerstatus -eq 2} | select name | sort name
#$GLOBAL:Bad2 = $GLOBAL:LPrinters | where {$_.printerstatus -eq 3 -and $_.name -ne "Microsoft XPS Document Writer"} | select name | sort name
#$GLOBAL:Bad = $GLOBAL:Bad1 + $GLOBAL:Bad2
if ($GLOBAL:Bad.count -gt 0) # If the array is greater than 0 then call the function to delete the printers
{DelPrinter}
Else
{Write-Host "No printers will be deleted" -ForegroundColor Yellow
LogI "$date No printers were deleted"}
}
Function DelPrinter # Function is called to delete printers if the array tests to be greater than 0
{
# Outputs the printers to a text file
$GLOBAL:Bad | Out-File $DelFile
# Assigns the text file contents to an array
$btext = gc $DelFile
# Removes the text file
#remove-item $DelFile
##########################-Formatting-##########################################
# Remove first four lines from the text file, spaces and blank lines
$btext[0],$btext[3..($btext.length-1)] | out-file $DelFile -encoding ascii
(gc $DelFile) | ? {$_.trim() -ne "" } | sc $DelFile -encoding ascii
(gc $DelFile) | Foreach {$_.TrimEnd()} | sc $DelFile -encoding ascii
(gc $DelFile) | where {$_ -ne ""} | sc $DelFile -encoding ascii
##########################-Formatting-###########################################
# Removing a Network Printer Connection
# Get the contents of the delete text file
$GLOBAL:Bad = (gc $DelFile)
# Reviews each item in the array and processes them seperately
foreach ($B in $Bad)
{
# Reinitializes date for more accurate reporting
$date2 = Get-Date
# Assigns the date and time to the printer being deleted to a variable
$LogDel = "$date2 $B"
# Logs the deletion of the printer
LogI "Deleted: $LogDel"
# Networked printer is now deleted
Write-Host "Deleting printer $B"
(New-Object -ComObject WScript.Network).RemovePrinterConnection("$B")
}
}
Function GNP # Function to Get Network Printers (GNP)
{
# Copies the printer map script to the local computer
Copy-Item \\ShareDrive\Sharefolder\ShareFile.vbs C:\temp\ShareFile.txt
}
Function FNP
{
# Assign the contents of the Network printer list to a variable
$NPrinters = Get-Content C:\temp\ShareFile.txt
##########################-Formatting-##########################################
#removes all text and formatting from the network printer list then assigns the contents to a new array
foreach ($NPrinter in $NPrinters)
{
$NPrinter1 = $NPrinter.split(" ")
$Printers = $NPrinter1[1]
$Printers1 = $($Printers -split '"')
$PL = $Printers1[1]|Where-Object {$_.length -gt 2}
$PL >> C:\temp\pl.txt
}
##########################-Formatting-##########################################
}
Function GIP
{
# Get the installed printers and write to a file
$GLOBAL:LPrinters | select name | sort name | Out-File C:\temp\LocalPrinters.txt
# Get the contents of the file and load into an array
$GLOBAL:ltext = gc C:\temp\Localprinters.txt
# Remove the old file
remove-item C:\temp\Localprinters.txt
}
Function FIP
{
# Format the data in the array by removing the first four lines and spaces from the array and output to the file
$GLOBAL:ltext[0],$GLOBAL:ltext[3..($GLOBAL:ltext.length-1)] | out-file C:\temp\Localprinters.txt -encoding ascii
# Removes blanks from the file and sets the contents with the new formatting
(gc C:\temp\Localprinters.txt) | ? {$_.trim() -ne "" } | sc C:\temp\Localprinters.txt -encoding ascii
# Removes the blank lines from the end of the file and sets the contents with the new formatting
(gc C:\temp\Localprinters.txt) | ForEach {$_.trimEnd()} | sc C:\temp\Localprinters.txt -encoding ascii
# Assigns the nice neat contents of the file back to the array
$GLOBAL:ltext = (gc C:\temp\Localprinters.txt)
}
Function COMP
{
# Begins comparing the two printer files
# Compares the files and outputs non-built printers to the NewPrinters.txt file
$FinalGroups = Compare-Object (gc C:\temp\pl.txt) (gc C:\temp\LocalPrinters.txt) |
where {$_.SideIndicator -eq "<="} |
select -ExpandProperty inputObject |
sort
#Removes duplicate printers from the list using the -uniq
$FinalGroups | select -uniq | Out-File C:\temp\NewPrinters.txt
$GLOBAL:FinalPrinters = gc C:\temp\NewPrinters.txt
}
Function PNP
{
# Test new printer connectivity
$PingFile = "C:\temp\NewPrinters.txt"
$PingFile
$Pings = gc $PingFile
# Get just the printer names from the New Print File and appends them to a new file called Working
foreach ($p in $Pings)
{
$np = $p.split("\\")
$to = $np[3]
$to >> C:\temp\working.txt
}
# Assigns the contents of the working file (new printers) to an array
$to = gc C:\temp\working.txt
foreach ($t in $to)
{
# Tests the printers connection
write-host "testing printer $t"
$ok = Test-Connection $t -Count 2 -Quiet
#Takes the connectivity results and determines to remove the printer from the file prior to build starting.
if ($ok -ne "TRUE")
{
write-host "$t Communication Failed" -ForegroundColor Red
# If the printer communication fails, the entry is removed from the NewPrinters.txt file
(gc "C:\temp\NewPrinters.txt") -notmatch "$t" | Out-file "C:\temp\NewPrinters.txt"
# Logs the removal of the printer and why it is being removed
#Reinitializes date for more accurate times in the log file
$date11 = Get-Date
$remprt = "$date11 - printer $t will not be built - communication failed"
LogI $remprt
}
else
{
Write-Host "$t Communication Successful" -ForegroundColor Yellow
}
}
}
Function BUILD
{
# Build each new printer found in the NewPrinters text file
$ToBuild = gc C:\temp\NewPrinters.txt
foreach ($item in $ToBuild)
{
# Reinitialized date to get more accurate reporting
$date4 = Get-Date
# Creates Logging info
$LogIt = "Created: $date4 $item"
# Calls function to write information to a log file
LogI $LogIt
Write-Host -NoNewLine "Creating printer $item" -ForegroundColor green
# Printer Build now occurs
(New-Object -ComObject WScript.Network).AddWindowsPrinterConnection("$item")
}
}
##############
####-MAIN-####
##############
# Cleanup High CPU and long running services which interfere with this script
ServiceShutdown
# Cycle the print spooler service
CycleSpooler
# Get Local Printers
GetLocalPrinters
# Archive log maintenance
ArchiveLog
# Starts logging
StartLog
# Get the completed job
`enter code here` $GLOBAL:LPrinters = Receive-Job -job $GLOBAL:job1 -keep | select $props
# Handles Bad pritners in a status of 2 "Printer not Found on Server, unable to connect"
BadPrinter
# Get Network printer list
GNP
# Format Network printer list
FNP
# Get installed/existing printers
GIP
# Format installed/existing printer file
FIP
# Compare existing printers with new printers only keep network printers needing to be built
COMP
# Check if New Printer File is NULL
if ($GLOBAL:FinalPrinters.count -gt 0)
{
# Ping new printer connection and remove printers with failed connections
PNP
# Build new printers
BUILD
}
Else
{
$date6 = Get-Date
LogI "$date6 No new printers were built"
}
# Cleanup temp text files
CleanupTMP
# Stops Logging
EndLog
# Cleanup Archive log files older than the specified ## of days
CleanupLogs
# Restarts Services
ServiceReenable
# Cycle the print spooler service
CycleSpooler
# Printer Maintenance is Complete
Write-Host "Printer Maintenance is complete" -ForegroundColor Red -BackgroundColor Yellow
Example of what is inside the VBS:
Set objNetwork = CreateObject("WScript.Network")
objNetwork.AddWindowsPrinterConnection "\\PrintServer\Printer1"
I do not control nor maintain this file. I am only allowed to run it. This script copies the .vbs to a local text file which is then edited as needed.