Reputation: 83
I am trying to get a list installed printers for a list of computer.
When I run this script, it only "writes" the last computer's information.
I am VERY new to PS and would appreciate some help.
$filePath = "E:\ps\computerswithprinters.txt"
$class = "win32_printer"
$arycomputer = Get-Content "E:\ps\computers.txt"
foreach( $computer in $aryComputer)
{
Write-Host "Retrieving printers from $computer ..."
$wmi = Get-WmiObject -Class $class -computername $computer
format-table -Property name, systemName, shareName -groupby driverName `
-inputobject $wmi -autosize | Out-File -FilePath $filePath
}
Thank you in advance!
Upvotes: 8
Views: 21025
Reputation: 173
Of course you forgot "Start-Transcript" but then you run into the problem of outputting all the data to the transcript. What I mean is that I have written a cleaner script (tweaked an existing one extensively) and this uses Start-Transcript to log the contents, but I find the log does not capture all the content, so the question is, do you want to WATCH the results or merely LOG the results. :) If you want to watch: Use 'Start-Transcript' and then verbose all your results. If you want to log it all then output to a file. Just remember to UnBlock-file the log variable's path at the end or it will remain locked.
Here is my Cleaner script that watches and logs:
#D:\batch\Patrick\Clean-ServersScript.ps1 #,,for testing new options
#THE server cleanup script that is to be scheduled and used everywhere
#Sets the function
Function Cleanup {
<#
.CREATED BY:
Matthew A. Kerfoot
.CREATED ON:
10\17\2013
.UPDATED BY:
Patrick J. Burwell
.LATEST UPDATE:
11:35 AM 10/26/2022
.Synopsis
Automated cleaning up of C VOLUME
Automated cleaning up of D VOLUME
.DESCRIPTION
Cleans the C: drive's Window Temporary files, Windows SoftwareDistribution folder, `
the local users Temporary folder, IIS/arcgis logs (if applicable) and empties the recycling bin. `
All deleted files will go into a log transcript in C:\Windows\Temp\.
By default this script leaves files that are newer than 30 to 45 days old...
...however, this variable may be edited on a per case basis.
.EXAMPLE
PS D:\batch> cleanup
Save the file to your desktop with a .PS1 extention and run the file from an elavated PowerShell prompt.
.NOTES
This script will typically clean up anywhere from 1GB up to 15GB of space from specified volumes.
.FUNCTIONALITY
PowerShell v4.x, v5.1
#>
function global:Write-Verbose ( [string]$Message )
# check $VerbosePreference variable, and turns -Verbose on
{ if ( $VerbosePreference -ne 'Continue' )
{ Write-Host " $Message" -ForegroundColor 'Yellow' } }
$VerbosePreference = "Continue"
$DaysToDelete = 1
$LogDate = get-date -format "MM-d-yy_HH'00hrs'"
$objShell = New-Object -ComObject Shell.Application
$objFolder = $objShell.Namespace(0xA)
$ErrorActionPreference = "Continue"
$systemname = [System.Net.Dns]::GetHostByName($env:computerName).HostName
#Creates logs folder if missing
if((test-path "D:\batch\logs\" -PathType Container) -ine $true){
md -force -path "D:\batch\logs\" -Verbose -EA SilentlyContinue
}
## Deletes the contents of the d:\batch\logs folder back 5 days.
gci -Recurse -Path d:\batch\log?\*.* -Exclude "*-Automation.txt" -EA SilentlyContinue |
Where-Object { ($_.CreationTime -lt $(Get-Date).AddDays(-5)) } | #<-- clears 5 days back
remove-item -force -Verbose -recurse -EA SilentlyContinue
#Remove old cleaner logs
unblock-file "d:\batch\logs\*-Clean-ServersScript.log" -ea SilentlyContinue
rm -Force "d:\batch\logs\*-Clean-ServersScript.log" -ea SilentlyContinue
#Begin Script
$LogDate = get-date -format "MM-d-yy_HH'00hrs'"
Start-Transcript -Path "D:\batch\logs\$LogDate-Clean-ServersScript.log" -Append
## Cleans all code off of the screen.
Clear-Host
#Enumerates ISO VHD and ZIP files with sizes in GB
$size = gci C:\Users\* -Include *.iso, *.vhd, *.zip -Recurse | #-EA SilentlyContinue | #Added zip extensions
Sort Length -Descending |
Select-Object Name,
@{Name="Size (GB)";Expression={ "{0:N2}" -f ($_.Length / 1GB) }}, Directory |
Format-Table -AutoSize | Out-String
$Before = Get-WmiObject Win32_LogicalDisk | Where-Object { $_.DriveType -eq "3" } | Select-Object SystemName,
@{ Name = "Drive" ; Expression = { ( $_.DeviceID ) } },
@{ Name = "Size (GB)" ; Expression = {"{0:N1}" -f( $_.Size / 1gb)}},
@{ Name = "FreeSpace (GB)" ; Expression = {"{0:N1}" -f( $_.Freespace / 1gb ) } },
@{ Name = "PercentFree" ; Expression = {"{0:P1}" -f( $_.FreeSpace / $_.Size ) } } |
Format-Table -AutoSize | Out-String
## Stops the windows update service if running and makes sure it is set to manual
$servicename = 'wuauserv'
$service = Get-Service -Name $servicename
if ($service.Status -eq 'Running') {
$service | Stop-Service
Write-Host "Windows Update Service has been stopped successfully!"
}
if ($service.StartType -eq 'Automatic') {
$service | Set-Service -StartupType Manual
Write-Host "Windows Update Service has been set to manual successfully!"
}
# Use below script If you need to start the service again
# $service | Set-Service -Status Running
#Cleanup Font Cache to 7 days
gci "C:\Windows\ServiceProfiles\LocalService\AppData\Local\*FONTCACHE*" -Recurse -Exclude "*.dll" -Force -Verbose -EA SilentlyContinue |
Where-Object { ($_.CreationTime -lt $(Get-Date).AddDays(-7)) } |
remove-item -force -Verbose -recurse -EA SilentlyContinue
## Deletes the contents of windows software distribution.
gci "C:\Windows\SoftwareDistribution\*" -Recurse -Force -Verbose -EA SilentlyContinue | remove-item -force -Verbose -recurse -EA SilentlyContinue
## The Contents of Windows SoftwareDistribution have been removed successfully!
## Deletes the contents of the Windows Temp folder.
gci "C:\Windows\Temp\*" -Recurse -Exclude "*.dll" -Force -Verbose -EA SilentlyContinue |
Where-Object { ($_.CreationTime -lt $(Get-Date).AddDays(-$DaysToDelete)) } |
remove-item -force -Verbose -recurse -EA SilentlyContinue
gci "C:\Temp\*" -Recurse -Exclude "*.dll" -Force -Verbose -EA SilentlyContinue |
Where-Object { ($_.CreationTime -lt $(Get-Date).AddDays(-$DaysToDelete)) } |
remove-item -force -Verbose -recurse -EA SilentlyContinue
## The Contents of Windows Temp have been removed successfully!
## Deletes all files and folders in user's AppData\Local\Temp folder.
gci -Recurse "C:\users\*\AppData\Local\Temp\*" -Exclude *.zip -Force -EA SilentlyContinue | #<-- added zip exclusion
Where-Object { ($_.CreationTime -lt $(Get-Date).AddDays(-5))} | #Changed to 5 days retention
remove-item -force -Verbose -recurse -EA SilentlyContinue
## The contents of C:\users\$env:USERNAME\AppData\Local\Temp\ have been removed successfully!
## Remove all files and folders in user AppData\Local\Microsoft\Windows\Temporary Internet Files\.
gci -FORCE "C:\users\*\AppData\Local\Microsoft\Windows\Temporary Internet Files\*" -Recurse -Verbose -EA SilentlyContinue |
Where-Object {($_.CreationTime -le $(Get-Date).AddDays(-$DaysToDelete))} |
remove-item -force -recurse -EA SilentlyContinue -verbose
## All Temporary Internet Files have been removed successfully!
## clears cache data in packages for all users
gci "C:\users\*\AppData\Local\Packages\*cache*\*" -Recurse -Force -Verbose -EA SilentlyContinue |
Where-Object {($_.CreationTime -le $(Get-Date).AddDays(-$DaysToDelete))} |`
remove-item -Recurse -Force -EA SilentlyContinue -Verbose
## clears Chrome caches for all users
Remove-Item -path “C:\Users\*\AppData\Local\Google\Chrome\User Data\Default\Cache\*” -Recurse -Force -EA SilentlyContinue -Verbose
Remove-Item -path “C:\Users\*\AppData\Local\Google\Chrome\User Data\Default\Cache2\entries\*” -Recurse -Force -EA SilentlyContinue -Verbose
Remove-Item -path “C:\Users\*\AppData\Local\Google\Chrome\User Data\Default\Cookies” -Recurse -Force -EA SilentlyContinue -Verbose
Remove-Item -path “C:\Users\*\AppData\Local\Google\Chrome\User Data\Default\Media Cache” -Recurse -Force -EA SilentlyContinue -Verbose
Remove-Item -path “C:\Users\*\AppData\Local\Google\Chrome\User Data\Default\Cookies-Journal” -Recurse -Force -EA SilentlyContinue -Verbose
# note that when you use '-ea silentlycontinue' with '-verbose' you only get action messages, not errors
## Cleans IIS Logs if applicable.
gci "C:\inetpub\logs\LogFiles\*" -Recurse -Force -EA SilentlyContinue |
Where-Object { ($_.CreationTime -le $(Get-Date).AddDays(-30)) } | #<--note the specialized date of 1 month
Remove-Item -Force -Verbose -Recurse -EA SilentlyContinue
## All IIS Logfiles over x days old have been removed Successfully!
## cleans all gdbimport_gpserver data
$limit = (Get-Date).AddDays(-1) #<-- sets a specialized date limit
$folder = "C:\Users\SVC-fim-app\AppData\Local\Temp\gdbvalidation_gpserver"
gci -Path $folder -Force -EA SilentlyContinue | Where-Object { $_.PSIsContainer -and $_.CreationTime -lt $limit} | Remove-Item -Force -Recurse -EA SilentlyContinue -Verbose
$folder = "C:\Users\SVC-fim-app\AppData\Local\Temp\gdbimport_gpserver"
GCI -Path $folder -Force -EA SilentlyContinue | Where-Object { $_.PSIsContainer -and $_.CreationTime -lt $limit } | Remove-Item -Force -Recurse -EA SilentlyContinue -Verbose
##Cleans all C VOL ESRI Desktop Staging data folders back from 3 days prior
#Like 'C:\Users\v051056\AppData\Local\ESRI\Desktop10.7\Staging'
if(test-path 'C:\Users\*\AppData\Local\ESRI\Desktop*\Staging'){
$limit = (Get-Date).AddDays(-3) #<-- sets a specialized date limit
$folder = "C:\Users\*\AppData\Local\ESRI\Desktop*\Staging\*.*"
$countfolders = (gci -Path $folder -Force -EA SilentlyContinue | Where-Object { $_.PSIsContainer -and $_.CreationTime -lt $limit})
Write-Host " The number of Staging files to be removed is" $countfolders.count
$countfolders | Remove-Item -Force -Recurse -EA SilentlyContinue -Verbose #use '-WhatIf' to be sure here
}
##Clears the GeoEvent Cache if older than 3 days on ArcGIS Geo servers
#ArcGIS\Server\GeoEvent\data\cache\bundle8\version0.0\bundle.jar
#ArcGIS\Server\GeoEvent\data\cache\
## clears user log
$equal = (gci -Recurse c:\users\*\log).name -eq "log" #<--Use a known good path to test
if($equal -eq $true){
write-host "...user logs exist... clearing..."
gci –Path d:\apps\ArcGIS\Server\GeoEvent\data\cache -Recurse -force -EA SilentlyContinue | Where-Object {($_.LastWriteTime -le (Get-Date).AddDays(-1))} | Remove-Item -EA SilentlyContinue -Verbose #<--Use for test purposes only
}
##Clears the Users CrashDumps if older than 1 day on servers
gci "C:\Users\*\AppData\Local\CrashDumps\*.dmp" -Recurse -Force -EA SilentlyContinue |
Where-Object { ($_.CreationTime -le $(Get-Date).AddDays(-1)) } | #<--note the specialized date of 1 month
Remove-Item -Force -Verbose -Recurse -EA SilentlyContinue
#To use if the prior fails
#$Folder = "C:\Users\*\AppData\Local\Crashdumps\*"
#Remove-Item $Folder -Force -Verbose -EA SilentlyContinue
##LiveKernelReports DMP file cleanups
if(Test-Path "C:\windows\LiveKernelReports" -PathType Container){
Remove-Item "C:\windows\LiveKernelReports\*.dmp" -Force -Verbose -Recurse -EA SilentlyContinue
}
## All CrashDUmp DMP files over 1 day old have been removed Successfully!
##Clears the Users Terminal Server Bin files if older than 1 day on servers
gci "C:\Users\*\AppData\Local\Microsoft\Terminal Server Client\Cache\*.bin" -Recurse -Force -EA SilentlyContinue |
Where-Object { ($_.CreationTime -le $(Get-Date).AddDays(-1)) } | #<--note the specialized date of 1 month
Remove-Item -Force -Verbose -Recurse -EA SilentlyContinue
## All CrashDUmp DMP files over 1 day old have been removed Successfully!
## clears user log
if(test-path c:\users\*\*log*){
write-host " ...user logs exist... clearing..."
unblock-file "c:\users\*\*log*\*.*" -Verbose
gci –Path "c:\users\*\*log*\*.*" -Recurse -hidden -Exclude "ntuser.dat*" -force -EA SilentlyContinue | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-1))} | Remove-Item -Exclude "ntuser.dat*" -Recurse -Force -Verbose -EA SilentlyContinue |Out-Null
}
## clears newrelic agent debug logs to 3 days
$equal = test-path $env:CORECLR_NEWRELIC_HOME\Logs\ -EA SilentlyContinue #<--Use a known good path for test purposes only
if ($equal -eq $true)
{
gci –Path "$env:CORECLR_NEWRELIC_HOME\Logs\debug_*.txt" -Recurse | Where-Object {($_.LastWriteTime -lt (Get-Date).AddDays(-3))} | Remove-Item -force -EA SilentlyContinue -Verbose #<-- set this for NewRelic Debug Logs
}
else{
#Write-Host "CORECLR_NEWRELIC_HOME\Logs\debug_*.txt doesn't exist."
Write-Host "$env:CORECLR_NEWRELIC_HOME\Logs\ has no NewRelic .Net debug logs"
}
## clears arcgis log data to 90 days, if it exists
if(test-path "d:\apps\arcgis\"){
gci "D:\arcgisserver\logs\$systemname\*.log" -Recurse -Force -Verbose -EA silentlyContinue | `
Where-Object {($_.CreationTime -le $(Get-Date).AddDays(-90))} |`
remove-item -Recurse -Force -EA SilentlyContinue -Verbose
}
## clears arcgis log data to 90 days, if it exists
if(test-path "c:\progra~1\arcgis\"){
gci "D:\arcgisserver\logs\$systemname\*.log" -Recurse -Force -Verbose -EA silentlyContinue | `
Where-Object {($_.CreationTime -le $(Get-Date).AddDays(-90))} |`
remove-item -Recurse -Force -EA SilentlyContinue -Verbose
}
## CleanMgr ONLY if after 2000 hrs
$TIMETOSTART = Get-Date -Format "dd/MM/yyyy HH:mm:ss" -Hour 20 -Minute 00 -Second 00 -Millisecond 00
if (((Get-Date).ToString('HH:mm')) -lt "$TIMETOSTART"){
if(test-path C:\Windows\System32\cleanmgr){& C:\Windows\System32\cleanmgr /VERYLOWDISK}}
#StartComponentCleanup task is located under the \Microsoft\Windows\Servicing section of the taskschd.msc.
#This task runs in the background and automatically removes component versions older than 30 days that have been superseded by newer files.
#schtasks.exe /Run /TN "\Microsoft\Windows\Servicing\StartComponentCleanup"
#The below is the same as the above
#DISM.exe /Online /Cleanup-Image /StartComponentCleanup
#Turn off localfile enumeration
openfiles /local off
#Placeholder for log4j2-scan
#md d:\batch\output;cd d:\batch\output;&d:\batch\log4j2-scan.exe --force-fix d:\install c:\users --report-csv
## deletes the contents of the recycling Bin.
Clear-RecycleBin -force -Verbose -Confirm:$false
Write-Host "The Recycling Bins have been emptied! "
if(test-path "D:\batch\RemProf08\Del_Prof.cmd"){
cd D:\batch\RemProf08\
if((test-path D:\batch\RemProf08\log) -ine $true){md D:\batch\RemProf08\log}
.\Del_Prof.cmd
}
cd d:\batch
##Set After Variable
sleep -Seconds 5
$After = Get-WmiObject Win32_LogicalDisk | Where-Object { $_.DriveType -eq "3" } | Select-Object SystemName,
@{ Name = "Drive" ; Expression = { ( $_.DeviceID ) } },
@{ Name = "Size (GB)" ; Expression = {"{0:N1}" -f( $_.Size / 1gb)}},
@{ Name = "FreeSpace (GB)" ; Expression = {"{0:N1}" -f( $_.Freespace / 1gb ) } },
@{ Name = "PercentFree" ; Expression = {"{0:P1}" -f( $_.FreeSpace / $_.Size ) } } |
Format-Table -AutoSize | Out-String
## Sends some before and after info for ticketing purposes
Hostname ; Get-Date | Select-Object DateTime
Write-Host "Before: $Before"
Write-Host "After: $After"
Write-Host $size
## Completed Successfully!
Stop-Transcript|Out-Null } Cleanup
Echo "Your Log file is D:\batch\logs\$LogDate-Clean-ServersScript.log"
Upvotes: 0