Unable to Output Data to text file - windows

I am using the following script to pull a list of all my computers from my wsus server. It then places then in a neat list and this works fine.
However, when I try to output the data to a text file it creates the text file but writes no data. Is there something I am missing in the Output part? Full script below.
$wsus = 'halvedge2'
[reflection.assembly]::LoadWithPartialName("Microsoft.UpdateServices.Administration") | Out-Null
$wsus = [Microsoft.UpdateServices.Administration.AdminProxy]::getUpdateServer()
$wsus.GetComputerTargets() | Select FullDomainName, LastReportedStatusTime, LastSyncTime
out-file -filepath "\\halvedge2\c$\PS1\WSUS\Last installed Update\updates.txt"
Additionally I would like to add an If statement to it looks at the LastSyncTime and for any LastSyncTime over 30 days it only returns them Computer Targets. How can I achieve this?

You do not have to out-file separately:
If the below yields value, then Instead of this:
$wsus.GetComputerTargets() | Select FullDomainName, LastReportedStatusTime, LastSyncTime
Do This:
$wsus.GetComputerTargets() | Select FullDomainName, LastReportedStatusTime, LastSyncTime | Out-File "D:\updates.txt" -Append -Force
Note: First try saving locally. If it works, then try remotely on the UNC. If remote fails, then give permission to the specific user to save it.

Related

Trying to write a powershell script that shows all locked files with computer names instead of IP address

The task given was to create a way for our staff to see who has the file open that they want to use, as Windows says it is either locked and doesn't name the person who has it locked, or it displays the person who made the file but not the person who currently has it open.
I can look it up in Computer Management on the fileserver, but were are hoping to speed up this for the end users.
I've written this powershell script on our fileserver and it works perfectly, I have this running every 5 minutes in Task Scheduler with administrative permissions:
get-smbopenfile -ClientUserName * |select clientcomputername,clientusername,path | Out-File -Encoding utf8 "S:\LockedFiles.txt" -width 300
The output looks like this:
clientcomputername clientusername path
------------------ -------------- ----
IPADDRESS DOMAIN\USERNAME S:\FOLDER\FILE.FILEEXTENSION
What I really want to do now is get the computer name rather than the IP address, just in case staff are logged into multiple machines at the same time.
I wondered if ClusterNodeName or PSComputerName would provide this, but the returned data is always blank.
I thought about this and below is one option (the first line is pseudocode), but as I see it that would mean recursively altering the piped data or reading in piped data, which I'm not even sure how to do.
$ipaddress = IPADDRESS
$Workstation = [System.Net.Dns]::GetHostByName($ipaddress)
Write-Host $Workstation.HostName
Anyone have any ideas on how I can do this? Is there a better way?
I assume you're looking to add a new property to your output object that has the resolved DNS Name from the IP Address found in the ClientComputerName property. For this you use Resolve-DnsName to attempt the name resolution and a Try Catch in case it fails to capture the exception message. For the export I would recommend you to use Export-Csv.
Get-SmbOpenFile -ClientUserName * | ForEach-Object {
$dnsName = try {
(Resolve-DnsName $_.ClientComputerName -ErrorAction Stop).NameHost
}
catch {
[ComponentModel.Win32Exception]::new($_.Exception.NativeErrorCode).Message
}
[pscustomobject]#{
ClientIpAddress = $_.ClientComputerName
ResolvedHostName = $dnsName
ClientUserName = $_.ClientUserName
Path = $_.Path
}
} | Export-Csv "S:\LockedFiles.csv" -Encoding utf8 -NoTypeInformation

Powershell script: List files with specific change date (Amount if possible)

For license porpuses I try to automate the counting process instead of having to login into every single server, go into directory, search a file name and count the results based on the change date.
Want I'm aiming for:
Running a powershell script every month that checks the directory "C:\Users" for the file "Outlook.pst" recursively. And then filters the result by change date (one month or newer). Then packing this into an email to send to my inbox.
I'm not sure if that's possible, cause I am fairly new to powershell. Would appreciate your help!
It is possible.
I dont know how to start a ps session on a remote computer, but I think the cmdlet Enter-PSSession will do the trick. Or at least it was the first result while searching for "open remote powershell session". If that does not work use the Invoke-Command as suggested by lit to get $outlookFiles as suggested below.
For the rest use this.
$outlookFiles = Get-ChildItem -Path "C:\Users" -Recurse | Where-Object { $_.Name -eq "Outlook.pst" }
Now you have all files that have this name. If you are not familiar with the pipe in powershell it redirects all objects it found with the Get-ChildItem to the next pipe section and here the Where-Object will filter the received objects. If the current object ($_) will pass the condition it is returned by the whole command.
Now you can filter these objects again to only include the latest ones with.
$latestDate = (Get-Date).AddMonths(-1)
$newFiles = $outlookFiles | Where-Object { $_.LastAccessTime -gt $latestDate }
Now you have all the data you want in one object. Now you only have to format this how you like it e.g. you could use $mailBody = $newFiles | Out-String and then use Send-MailMessage -To x#y.z -From r#g.b -Body $mailBodyto send the mail.

How to get a comma separated table of installed Windows programs using PowerShell?

I need to get a list of installed programs on my computer (Windows 10) in a comma separated format showing the name of the program and version in a format like this: Program Name,Version
What I have tried:
I am currently using this Windows PowerShell command:
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion | Format-Table –AutoSize
This gets me a table that looks like this:
I would like it to look something like this (The table header format is not important):
Is there a way to format the table that would accomplish this or another PowerShell command that would produce an output similar to the second table?
Try something like this:
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion | ConvertTo-Csv -NoTypeInformation
See also Export-Csv.

Coallate logs by date/time, from seperate servers, with powershell

I'd like to have a script that grabs the logs from a list of paths and sorts all the entries in the logs into one large consolidated log. I'm fairly new at programming and powershell, but I've got a start. The log entries look like this:
2013-07-17 05:00:00,003 INFO [com.mpi.mp.viewer.web.servlet.ViewerLogFlusher] Skipped sending the empty string to wmsiislo
What I'm thinking is that I need to somehow parse each line into a multidimensional array, and sort it. The problem is, I can't get the hang of the [DateTime] method. My very incomplerte code is below:
#Code to append all logs together
$Biglog = Get-Content C:\Temp\logs\server1.log
foreach ($line in $Biglog){
#do something
}
try this :
ls c:\temp\logs\*.log | gc | out-file c:\temp\log.txt
Import-Csv C:\temp\log.txt -Header "date","info" |Sort-Object date | export-csv c:\temp\sortedlogs.csv

Extract hostnames from Perfmon blg with Powershell

I'm writing a script which will automate the extraction of data from .blg Perfmon logs.
I've worked out the primary Import-Counter commands I will need to use to get the data out, but am trying to parametrise this so that I can do it for each machine in the log file (without having to open the log up in Perfmon, which can take 15 minutes or sometimes more, and is the reason I'm writing this script), and find out what each hostname is.
The script I have does the job, but it still takes a minute to return the data I want, and I wondered if there was a simpler way to do this, as I'm not too familiar with Powershell?
Here's what I have:
$counters = Import-Counter -Path $log_path$logfile -ListSet * | Select-Object paths -ExpandProperty paths
$svrs = #()
# for each line in the list of counters, extract the name of the server and add it to the array
foreach ($line in $counters) {
$svrs += $line.split("\")[2]
}
# remove duplicates and sort the list of servers
$sorted_svrs = $svrs | sort -unique
foreach ($svr in $sorted_svrs) {
Write-Host $svr
}
I'm just printing the names for the moment, but they'll go into an array in the proper script, and then I'll run my Import-Counter block with each of these hosts parametrised in.
Just wondered if there was a better way of doing this?
$sorted_svrs=Import-Counter "$log_path$logfile" -Counter "\\*\physicaldisk(_total)\% disk time" | %{$_.countersamples.path.split("\")[2]} | sort -Unique

Resources