I have a problem with my Script.
I wanted to make a Script which makes a list of software which is found in a specific registry path
and see if this software equals installed software. and if so it should output me the uninstall string.
but right now it does not work as wanted. it never show me the output I wanted even if its similar. As Example i have the Program Git as Branding and in the software I got Git version 2.26.2 but it wont output the uninstall string when I selected git.
My code is:
$branding = Get-ChildItem "HKLM:\Software\DLR\Branding" | Get-ItemProperty | Select-Object -expandProperty ProgramName
$software = Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall, HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall | Get-ItemProperty | Select-Object -ExpandProperty DisplayName
ForEach ($brandinglist in $branding) {
$objCombobox.Items.Add("$brandinglist")
}
$objComboBox_SelectedIndexChanged=
{
$selectme = $objCombobox.SelectedItem
Write-Host $selectme
if ("$selectme" -like "*$software*") {
$uninstall = Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall, HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall | Get-ItemProperty | Where-Object {$_.DisplayName -match "$electme" } | Select-Object -Property UninstallString
Write-Host "$uninstall"
}
}
You are trying the -like comparison wrong, in which you compare the selected item to an array of displaynames which doesn't work that way.
Also, there is no reason to get the Uninstall strings and Displaynames using an almost identical code twice.
Try
# get a string array of program names
$branding = Get-ChildItem -Path 'HKLM:\Software\DLR\Branding' | Get-ItemProperty | Select-Object -ExpandProperty ProgramName
$regPaths = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall', 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall'
# get an object array of DisplayName and UninstallStrings
$software = Get-ChildItem -Path $regPaths | Get-ItemProperty | Select-Object DisplayName, UninstallString
# fill the combobox with the (string array) $branding
$objCombobox.Items.AddRange($branding)
$objComboBox.Add_SelectedIndexChanged ({
$selectme = $objCombobox.SelectedItem
Write-Host $selectme
# get the objects that have a displayname like the selected item and write out the matching Uninstall strings
$software | Where-Object {$_.DisplayName -like "*$selectme*" } | ForEach-Object {
Write-Host $_.UninstallString
}
})
Related
I want to keep only the file with the largest version of the specified zip file in the folder using powershell. I wrote a shell script but it returns all the files. How can I modify the script to select only the file with the largest version?
$files = Get-ChildItem -Filter "*.zip"
$max = $files |Measure-Object -Maximum| ForEach-Object {[int]($_.Split("_")[-1].Split(".")[0])}
$largestFiles = $files | Where-Object {[int]($_.Split("_")[-1].Split(".")[0]) -eq $max}
Write-Output $largestFiles
Expectation:
A1_Fantasic_World_20.zip
A1_Fantasic_World_21.zip
B1_Mythical_Realms_11.zip
B1_Mythical_Realms_12.zip
C1_Eternal_Frame_Corporation_2.zip
C1_Eternal_Frame_Corporation_3.zip
↓
A1_Fantasic_World_21.zip
B1_Mythical_Realms_12.zip
C1_Eternal_Frame_Corporation_3.zip
A1_Fantasic_World's biggest number is 21.B1_Mythical_Realms's is 12.C1_Eternal_Frame_Corporation's is 3. So I want to choose the biggest version of zip.
First you add the calculated properties to your file system objects you use for filtering. Then with a combination of Group-Object, Sort-Object and Select.Object you can filter the desired files.
$FileList =
Get-ChildItem -Filter *.zip |
Select-Object -Property *,
#{
Name = 'Title'
Expression = {($_.BaseName -split '_')[0..$(($_.BaseName -split '_').count - 2)] -join '_' }
},
#{
Name = 'Counter'
Expression = {[INT]($_.BaseName -split '_')[-1]}
}
$LastOnesList =
$FileList |
Group-Object -Property Title |
ForEach-Object {
$_.Group | Sort-Object -Property Counter | Select-Object -Last 1
}
$LastOnesList |
Select-Object -Property Name
We currently have the following folder structure:
C:\Packages\Adobe\DC\9.2.2
C:\Packages\Adobe\DC\10.0.3
C:\Packages\Adobe\DC\10.0.8
C:\Packages\Microsoft\Edge\6.1.10
C:\Packages\Microsoft\Edge\6.1.18
C:\Packages\Microsoft\Edge\6.1.20
With a PowerShell script I try to keep only the highest version of the respective application folder and delete all others. The result should be:
C:\Packages\Adobe\DC\10.0.8
C:\Packages\Microsoft\Edge\6.1.20
However, the sorting doesn't seem to work properly in my script.
$folders_root = Get-ChildItem -Path C:\Packages -Directory
foreach ($folder in $folders_root)
{
$folders_appilcation = Get-ChildItem $folder.FullName -Directory
foreach ($app_folder in $folders_appilcation)
{
$versionfolder = Get-ChildItem $app_folder.FullName -Directory | Sort-Object -Descending | Select-Object -Skip 1 | % {Write-host "Deleting $($_.FullName)"<#; Remove-Item $_.FullName#>}
}
}
For the path "C: \ Packages \ Adobe \ DC" 9.2.2 is considered as the highest version (according to the script) but it should be 10.0.8.
Deleting C:\Packages\Adobe\DC\10.0.8
Deleting C:\Packages\Adobe\DC\10.0.3
Deleting C:\Packages\Microsoft\Edge\6.1.18
Deleting C:\Packages\Microsoft\Edge\6.1.10
Can someone tell me what I'm doing wrong?
Sort is comparing strings and not numbers. When you compare the string 10 and 9 it will interpret the 10 as a 1.
Force the sort to us it as version, try something like that:
sort {[version]::Parse(($_.split("\"))[-1])} -Descending
Thank you. The following code works perfectly:
$folders_root = Get-ChildItem -Path \\hkt-cmgmt01a\d$\Empirum\Configurator\Packages -Directory
foreach ($folder in $folders_root)
{
$folders_appilcation = Get-ChildItem $folder.FullName -Directory
foreach ($app_folder in $folders_appilcation)
{
$versionfolder = Get-ChildItem $app_folder.FullName -Directory | Sort-Object { [version] $_.Name } -Descending -ErrorAction SilentlyContinue| Select-Object -Skip 1 | % {Write-host "Deleting $($_.FullName)"<#; Remove-Item $_.FullName#>}
}
}
I want to get a list of all ad computers excluding the servers that are in a text file. Here's my code:-
$excludedServers = (Get-Content
"C:\Users\testuser\Documents\RdpDisconnectedSessions\ExcludedServers.txt").name #| Sort-Object
Get-ADComputer -Filter * | Where { $_.DistinguishedName -like "*Computers*" -and $_.DistinguishedName -notmatch $excludedServers } | Select-Object Name
Any advise please ?
First, Get-Content is not going to bring back objects so the .name portion is not going to work. If it's just a list of computernames, then simply change it to.
$excludedServers = Get-Content "C:\Users\testuser\Documents\RdpDisconnectedSessions\ExcludedServers.txt"
If it's a CSV with a name column, then you can do it a few ways. Sticking with the format you had this would work
$excludedServers = (Import-Csv "C:\Users\testuser\Documents\RdpDisconnectedSessions\ExcludedServers.txt").name
Now that you have your list of names, you can filter like this (assuming it is actually the names of the servers and not their distinguished name)
Get-ADComputer -Filter * | Where { $_.DistinguishedName -like "*Computers*" -and $_.name -notin $excludedServers } | Select-Object Name
I've been tasked with creating a script that checks to see if the office cameras we've set up have stopped uploading their feeds to the "Camera" share located on our Windows 2016 storage server. If the NEWEST .mkv is over an hour old compared to the current time (get-date) then the "problem" camera needs to be restarted manually. (No need to script that part.)
Here's what my Director has written so far:
#Variable Definitions start here
$numhours = 1
Get-ChildItem "d:\Shares\Cameras" | Foreach {
$folderToLookAt = ($_.FullName + "\*.mkv")
$result = Get-ChildItem -Recurse $folderToLookAt | Sort-Object CreationTime -Descending
echo $result[0].FullName
echo $result[0].CreationTime
}
The first variable really isn't used yet, but I'm kind of dumb-struck as what to do next. The above returns the full names and creation times successfully of the newest .mkvs
Suggestions on the next part?
Invert the logic - instead of searching all the files, sorting them, finding the most recent, and checking the date, do it the other way round.
Look for files created since the cutoff, and alert if there were none found:
$cutOffTime = [datetime]::Now.AddHours(-1)
Get-ChildItem "d:\Shares\Cameras" | Foreach {
$folderToLookAt = ($_.FullName + "\*.mkv")
$result = Get-ChildItem -Recurse $folderToLookAt | Where-Object { $_.CreationTime -gt $cuttoffTime }
if (-not $result)
{
"$($_.Name) has no files since the cutoff time"
}
}
I'm assuming your paths look like:
D:\Shares\Cameras\Camera1\file1.mkv
D:\Shares\Cameras\Camera1\file2.mkv
D:\Shares\Cameras\Camera2\file1.mkv
D:\Shares\Cameras\Camera2\file2.mkv
D:\Shares\Cameras\Camera3\file1.mkv
.
.
.
If so, I would do something like this:
# The path to your files
$CameraShareRoot = 'D:\Shares\Cameras';
# Number of Hours
$NumberOfHours = 1;
# Date and time of significance. It's $NumberOfHours in the past.
$MinFileAge = (Get-Date).AddHours( - $NumberOfHours);
# Get all the folders at the camera share root
Get-ChildItem -Path $CameraShareRoot -Directory | ForEach-Object {
# Get the most recently created file in each folder
$_ | Get-ChildItem -Recurse -Filter '*.mkv' -File | Sort-Object -Property CreationTime -Descending | Select-Object -First 1
} | Where-Object {
# Remove any files that were created after our datetime
$_.CreationTime -lt $MinFileAge;
} | Select-Object -Property FullName, CreationTime
This will just output the full file name and creation time for stale cameras.
You could do something like this to email yourself a report when the results have any files:
# The path to your files
$CameraShareRoot = 'D:\Shares\Cameras';
# Number of Hours
$NumberOfHours = 1;
# Date and time of significance. It's $NumberOfHours in the past.
$MinFileAge = (Get-Date).AddHours( - $NumberOfHours);
# Get all the folders at the camera share root, save the results to $StaleCameraFiles
$StaleCameraFiles = Get-ChildItem -Path $CameraShareRoot -Directory | ForEach-Object {
# Get the most recently created file in each folder
$_ | Get-ChildItem -Recurse -Filter '*.mkv' -File | Sort-Object -Property CreationTime -Descending | Select-Object -First 1;
} | Where-Object {
# Remove any files that were created after our datetime
$_.CreationTime -lt $MinFileAge;
}
# If there are any stale camera files
if ($StaleCameraFiles) {
# Send an email
$MailMessage = #{
SmtpServer = 'mail.example.com';
To = 'youremail#example.com';
From = 'youremail#example.com';
Subject = 'Stale Camera Files';
Body = $StaleCameraFiles | Select-Object -Property FullName, CreationTime | ConvertTo-Html -Fragment | Out-String;
BodyAsHtml = $true;
}
Send-MailMessage #MailMessage;
}
Generally you will want to use LastWriteTime instead of CreationTime since the latter can be updated by a file move or copy, but maybe that's what you want here.
You have to compare the CreationTime date with (Get-Date).AddHours(-1). The AddHours method allows you to add hours to the DateTime, but also to subtract.
You can use the following example:
$Path = 'd:\Shares\Cameras'
$CreationTime = Get-ChildItem -Path $Path -Filter *.mkv |
Sort-Object -Property CreationTime -Descending |
Select-Object -First 1 -ExpandProperty CreationTime
if ($CreationTime -lt (Get-Date).AddHours(-1)) {
# your action here (restart, send mail, write output, ...)
}
It also optimizes your code a bit. ;)
$LatestFile = Get-ChildItem C:\Users\Connor\Desktop\ | Sort CreationTime | Select -Last 1
if ($LatestFile.CreationTime -gt (Get-Date).AddHours(-1)){
#It's Currently Working
} else {
#Do Other Stuff
}
try this :
Get-ChildItem "c:\temp" -Filter *.mkv -File | sort CreationTime -Descending |
select -First 1 | where CreationTime -lt (Get-Date).AddHours(-1) |
%{Write-Host "Alert !!" -ForegroundColor Red}
Are there any cool cmdlets that will help me do the following?
I want something in Powershell that is as simple as doing the same in SQL:
select RootElementName , count(*) from Table
group by RootElementName
order by RootElementName
I'm all XML files in a directory, finding the root element of each XML file.
$DirectoryName = "d:\MyFolder\"
$AllFiles = Get-ChildItem $DirectoryName -Force
foreach ($Filename in $AllFiles)
{
$FQFilename = $DirectoryName + $Filename
[xml]$xmlDoc = Get-Content $FQFilename
$rootElementName = $xmlDoc.SelectSingleNode("/*").Name;
Write-Host $FQFilename $rootElementName
}
Desired Result:
RootName Count
-------- -----
Root1 15
MyRoot 16
SomeRoot 24
I know I could could either create two arrays, or an array of objects, store the root elements in the array, and do the counts all using typical code, was just hoping that this new language might have something built-in that I haven't discovered yet.
Could I pipe the "Write-Host $FQFilename $rootElementName " to something that would behave something to the SQL I referred to above?
You can get groups and counts by using Group-Object like this:
$AllFiles | Group-Object RootElementName | Sort-Object Name | Select-Object Name, Count
In your current example, Write-Host doesn't write an object to the pipeline that we can sort or group. Write-Host only prints text to the screen to show the user something, ex. a script menu.
$DirectoryName = "d:\MyFolder\"
$AllFiles = Get-ChildItem $DirectoryName -Force | ForEach-Object {
#The FullName-property contains the absolute path, so there's no need to join the filename and $directoryname
[xml]$xmlDoc = Get-Content $_.FullName
$rootElementName = $xmlDoc.SelectSingleNode("/*").Name
#Outputing an object that we can group and sort
New-Object -TypeName psobject -Property #{
FileName = $_.FullName
RootElementName = $rootElementName
}
}
$grped = $AllFiles | Group-Object RootElementName | Sort-Object Name | Select-Object Name, Count
I'm creating an object with a FileName-property and the RootElementName so you have it if you need to retrieve the filename+rootelement for a list. If not, we could simplify this to:
$DirectoryName = "d:\MyFolder\"
$AllFiles = Get-ChildItem $DirectoryName -Force | ForEach-Object {
#The FullName-property contains the absolute path, so there's no need to join the filename and $directoryname
[xml]$xmlDoc = Get-Content $_.FullName
#Output rootelementname
$xmlDoc.SelectSingleNode("/*").Name
}
$grped = $AllFiles | Group-Object | Sort-Object Name | Select-Object Name, Count