Can someone help me with this powershell script?
I can't get it to work.
$drives = Get-WmiObject -class win32_logicaldisk |
Where-Object { $_.DriveType -eq 3 }
$drives | ForEach-Object { Enable-ComputerRestore $_.Name }
Moreover the following works like expected!
$drives = Get-WmiObject -class win32_logicaldisk |
Where-Object { $_.DriveType -eq 3 }
$drives | ForEach-Object { Write-Host $_.Name }
Thanks in advance.
Enable-ComputerRestore seems to have two unusual requirements:
The (positionally implied) -Drive argument(s) must end in \ (backslash), e.g, C:\
In order to target a drive other than the system drive, the system drive must also be specified, alongside the non-system drive or System Restore must already be turned on for the system drive.
Since your code enumerates all local disks (.DriveType -eq 3), the system drive is by definition among them, so the simplest solution is to pass all local drives at once to Enable-ComputerRestore, as an array:
$driveSpecs =
Get-CimInstance -Class Win32_LogicalDisk |
Where-Object { $_.DriveType -eq 3 } |
ForEach-Object { $_.Name + '\' }
Enable-ComputerRestore $driveSpecs
As an aside:
I've replaced Get-WmiObject with Get-CimInstance, because the CIM cmdlets superseded the WMI cmdlets in PowerShell v3 (released in September 2012). Therefore, the WMI cmdlets should be avoided, not least because PowerShell Core (version 6 and above), where all future effort will go, doesn't even have them anymore. For more information, see this answer.
A more concise and more efficient way to filter the Get-CimInstance output is to use a -Filter argument in lieu of a separate Where-Object call:
Get-CimInstance -Class Win32_LogicalDisk -Filter 'DriveType = 3'
Found the solution by my self. Posting for others.
$OSDriveLetter = (Get-ComputerInfo | Select-Object -Property "OsSystemDrive").OsSystemDrive
Get-CimInstance -class win32_logicaldisk |
Where-Object { $_.DriveType -eq 3 } |
ForEach-Object { Enable-ComputerRestore "$($_.Name + '\')", "$($OSDriveLetter + '\')" }
Related
The majority of this code was pulled from a blog online, but I think it's exactly the way I need to be tackling this. I want to get the top 4 machines from an OU based on uptime, and run a script that lives on each of the top 4 machines. I know that the problem involves the Array losing access to the Get-ADComputer properties, but I'm unsure of how to pass these new properties back to their original objects. This works as expected until it gets to the foreach loop at the end.
$scriptBlock={
$wmi = Get-WmiObject -Class Win32_OperatingSystem
($wmi.ConvertToDateTime($wmi.LocalDateTime) – $wmi.ConvertToDateTime($wmi.LastBootUpTime)).TotalHours
}
$UpTime = #()
Get-ADComputer -Filter 'ObjectClass -eq "Computer"' -SearchBase "OU=***,OU=***,OU=***,DC=***,DC=***" -SearchScope Subtree `
| ForEach-Object { $Uptime += `
(New-Object psobject -Property #{
"ComputerName" = $_.DNSHostName
"UpTimeHours" = (Invoke-Command -ComputerName $_.DNSHostName -ScriptBlock $scriptBlock)
}
)
}
$UpTime | Where-Object {$_.UpTimeHours -ne ""} | sort-object -property #{Expression="UpTimeHours";Descending=$true} | `
Select-Object -Property ComputerName,#{Name="UpTimeHours"; Expression = {$_.UpTimeHours.ToString("#.##")}} | Select-Object -First 4 |`
Format-Table -AutoSize -OutVariable $Top4.ToString()
foreach ($Server in $Top4.ComputerName) {
Invoke-Command -ComputerName $Server -ScriptBlock {HOSTNAME.EXE}
}
I'm not married to Invoke-Command in the last foreach but am having the same issues when I try to use psexec. Also, I'm running hostname.exe as a check to make sure I'm looping through the correct machines before I point it at my script.
Here's a streamlined version of your code, which heeds the comments on the question:
# Get all computers of interest.
$computers = Get-ADComputer -Filter 'ObjectClass -eq "Computer"' -SearchBase "OU=***,OU=***,OU=***,DC=***,DC=***" -SearchScope Subtree
# Get the computers' up-times in hours.
# The result will be [double] instances, but they're also decorated
# with .PSComputerName properties to identify the computer of origin.
$upTimes = Invoke-Command -ComputerName $computers.ConputerName {
((Get-Date) - (Get-CimInstance -Class Win32_OperatingSystem).LastBootUpTime).TotalHours
}
# Get the top 4 computers by up-time.
$top4 = $upTimes | Sort-Object -Descending | Select-Object -First 4
# Invoke a command on all these 4 computers in parallel.
Invoke-Command -ComputerName $top4.PSComputerName -ScriptBlock { HOSTNAME.EXE }
Why does Get-CimInstance CIM_LogicalDisk return both a Win32_LogicalDisk and a Win32_MappedLogicalDisk?
There is a Win32_MappedLogical disk CIM class, but there is no Cim_MappedLogicalDisk` class. Should there be?
In pwsh 6 there does not appear to be one either. There are no CIM cmdlets in pwsh 6 on Linux. Is CIM a Microsoft-only thing? I thought not.
C:>$Provider = Get-CimInstance CIM_LogicalDisk | Where-Object { $_.Name -eq 'W:' }
C:>$Provider.Count
2
CIM_LogicalDisk returns both local and mapped logical disk objects. You can match on the Win32_LogicalDisk or CIM_LogicalDisk types like so:
$Provider = Get-CimInstance CIM_LogicalDisk | Where-Object {
$_.Name -eq 'W:' -And $_.CimClass.CimClassName -match '^(CIM|Win32)_LogicalDisk$'
}
This should omit the Win32_MappedLogicalDisk object from $Provider.
As for your question about no CIM cmdlets on Posh in Linux, this Powershell Github issue from April states, "There are no plans to port the CIM cmdlets to non-Windows."
Overall my goal is to get the VNC version for a list of remote computers along with the uninstall GUID so I can remotely uninstall VNC Viewer from certain computers. I have used the Get-WmiObject -Class Win32_Product but that is extremely slow.
I have the following script but in the results it includes the name of the select-object parameter.
$computers = Get-Content -Path "C:\Computers.txt"
$Results = #()
ForEach ($Computer in $Computers) {
$Results += New-Object PSObject -Property #{
"ComputerName" = $Computer
"Name" = Invoke-Command -ComputerName $Computer -ScriptBlock { Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* } `
| Where-Object -FilterScript {$_.DisplayName -like "VNC V*"} | select-object DisplayName
"DisplayVersion" = Invoke-Command -ComputerName $Computer -ScriptBlock { Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* } `
| Where-Object -FilterScript {$_.DisplayName -like "VNC V*"} | select-object DisplayVersion
"ModifyPath" = Invoke-Command -ComputerName $Computer -ScriptBlock { Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* } `
| Where-Object -FilterScript {$_.DisplayName -like "VNC V*"} | select-object ModifyPath
"Vendor" = Invoke-Command -ComputerName $Computer -ScriptBlock { Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* } `
| Where-Object -FilterScript {$_.DisplayName -like "VNC V*"} | select-object Publisher
}
}
$Results | Select-Object ComputerName,Name,DisplayVersion,ModifyPath,Vendor | Sort-Object ComputerName | Export-Csv C:\VNC.csv -notype ;
My results look like this:
ComputerName : ComputerName
Name : #{DisplayName=VNC Viewer 5.2.3}
DisplayVersion : #{DisplayVersion=5.2.3}
ModifyPath : #{ModifyPath=MsiExec.exe /I{18B1E36F-0DA3-4FDA-BC57-DD815B0DF3B2}}
Vendor : #{Publisher=RealVNC Ltd}
I would want it to look like this:
ComputerName : ComputerName
Name : VNC Viewer 5.2.3
DisplayVersion : 5.2.3
ModifyPath : MsiExec.exe /I{18B1E36F-0DA3-4FDA-BC57-DD815B0DF3B2}
Vendor : RealVNC Ltd
Is this possible or am I going about this script entirely wrong? I haven't figured out a way to run this Invoke-Command for multiple parameters and still output the results in individual columns any other way.
This script works but takes forever for 100's of computers:
if (Test-Path C:\VNCInstalled.csv) {Remove-Item C:\VNCInstalled.csv}
if (Test-Path C:\Computers.txt) {Remove-Item C:\Computers.txt}
$DirSearcher = New-Object System.DirectoryServices.DirectorySearcher([adsi]'')
$DirSearcher.Filter = '(&(objectClass=Computer)(!(cn=*esx*)) (!(cn=*slng*)) (!(cn=*dcen*)) )'
$DirSearcher.FindAll().GetEnumerator() | sort-object { $_.Properties.name } `
| ForEach-Object { $_.Properties.name }`
| Out-File -FilePath C:\Computers.txt
Get-Content -Path c:\Computers.txt `
| ForEach-Object {Get-WmiObject -Class Win32_Product -ComputerName $_} `
| Where-Object -FilterScript {$_.Name -like "VNC V*"} `
| select-object #{Name="ComputerName";Expression={$_.PSComputerName}},
Name,
#{Name="InstallLocation";Expression={$_.PackageCache}},
Vendor,
Version,
#{Name="GUID";Expression={$_.IdentifyingNumber}} `
| Sort-Object ComputerName `
| Export-CSV -path c:\VNCInstalled.csv -notype
Change all of your Select-Object commands to Select-Object
-ExpandProperty PropertyName, to discard the property name / column header.
This is the answer I gave three years ago and I think it was really a poor answer. Let me do a better job now.
Why your current code is slow
Your current code enumerates all machines from AD and puts them in a file called Computers.txt. Simple, and you do it fine.
Next up, your code performs this operation:
Get-Content -Path c:\Computers.txt |
ForEach-Object {Get-WmiObject -Class Win32_Product -ComputerName $_} `
| Where-Object -FilterScript {$_.Name -like "VNC V*"} [...]
This can be summarized as 'For each computer, request the full Win32_product table, and then after that, filter down to apps named VNC.' This is HUGELY performance impacting and for a few reasons.
Even on a fast modern computer, querying Win32_Product will take 30 seconds or more, because it returns every application installed. (on a new VM for me it took more than a minute with just a handful of apps installed!)
Querying Win32_Product also has this fun quirk which makes it take even longer, quoted from MSDN Documentation on the Win32_Product Class
Warning Win32_Product is not query optimized. Queries such as "select * from Win32_Product where (name like 'Sniffer%')" require WMI to use the MSI provider to enumerate all of the installed products and then parse the full list sequentially to handle the “where” clause. This process also initiates a consistency check of packages installed, verifying and repairing the install. With an account with only user privileges, as the user account may not have access to quite a few locations, may cause delay in application launch and an event 11708 stating an installation failure. For more information, see KB Article 794524.
So to summarize, querying Win32_Product is slow, AND it also triggers a consistency chceck on every app, AND we also have this query written to retrieve every single app before filtering. These add up to a process which probably takes ~3 minutes per pc, and will operate serially (one after the other) and take forever.
How to fix it
Software info can be retrieved reliably in two places:
If you have SCCM/ConfigMgr installed on your devices, it adds the Win32_AddRemoveProgram WMI Class you can query, which is a super fast version of Win32_Product
If not, we can always retrieve info from the registry.
Here's a short snippet to get applications like VLC installed on a computer (I don't have VNC like you, so I'm making due)
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Where-object DisplayName -like "VLC*" |Select-Object DisplayName, DisplayVersion, Publisher, InstallDate,UninstallString
DisplayName : VLC media player
DisplayVersion : 3.0.8
Publisher : VideoLAN
InstallDate :
UninstallString : "C:\Program Files (x86)\VideoLAN\VLC\uninstall.exe"
This operation is much faster, only 400 MS or so. Sadly we cannot get much faster using the registry as it has a very weird PowerShell provider that doesn't implement the -Filter parameter, so we do have to retrieve all programs and then filter to our desired choice.
Updating your script to use this function instead
I took the liberty of rewriting your script to use this approach, and restructured it a bit for better readability.
$results = New-object System.Collections.ArrayList
$computers = Get-Content -Path c:\Computers.txt
foreach ($computer in $computers){
#get VNC entries from remote computers registry
$VNCKeys = Invoke-Command -ComputerName $computer -ScriptBlock {
Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* |
Where-object DisplayName -like "VNC V*" |
Select-Object DisplayName, DisplayVersion, Publisher, UninstallString, #{Name=‘ComputerName‘;Expression={$computer}}
}#end of remote command
if ($VNCKeys -ne $null){
forEach($VNCKey in $VNCKeys){
[void]$results.Add($VNCKey)
}
}
}
$results | Sort-Object ComputerName | Export-CSV -path c:\VNCInstalled.csv -NoTypeInformation
I am trying to provide a list of servers in our domain that lists 2003 and 2008/r2 servers. Along with this information i would like to give the current status of their individual C Drive "free space" & "size of the disk". The script below runs fine and prints a list of all the correct operating systems - But...
The free space and Size are all identical..it gives the first servers drive status and replicates this untill the script finishes. for example the script prints:
serverName1 Windows server 2003 standard deviceid=c freespace=40gb size=12gb
serverName2 Windows server 2008r2 standard deviceid=c freespace=40gb size=12gb
....
serverName100 ..... freespace=40gb size=12gb
Import-Module activedirectory
$2008LogPath = "e:/2008servers.txt"
$2003LogPath = "e:/2003servers.txt"
$servers = get-adcomputer -Filter 'ObjectClass -eq "Computer"' -properties "OperatingSystem"
foreach ($server in $servers) {
if($server.OperatingSystem -match "Windows Server 2008") {
Get-WmiObject win32_logicaldisk | Where-Object {$_.deviceid -match "C"} |
ft $server.name, $server.operatingsystem, deviceid, freespace, size -AutoSize }#Out-File -Append $2008LogPath }
elseif($server.operatingsystem -match "Windows Server 2003") {
Get-WmiObject win32_logicaldisk | Where-Object {$_.deviceid -match "C"} |
ft $server.name, $server.operatingsystem, deviceid, freespace, size -AutoSize }#Out-File -Append $2003LogPath }
}
You'll need to use the -ComputerName parameter of the Get-WmiObject cmdlet, to retrieve information from those remote computers. If you don't specify the -ComputerName parameter, then you're retrieving WMI data from the local computer.
To fix this, change your foreach loop to look like the following:
foreach ($server in $servers) {
if($server.OperatingSystem -match "Windows Server 2008") {
Get-WmiObject -ComputerName $Server.Name -Class win32_logicaldisk | Where-Object {$_.deviceid -match "C"} |
ft $server.name, $server.operatingsystem, deviceid, freespace, size -AutoSize }#Out-File -Append $2008LogPath }
elseif($server.operatingsystem -match "Windows Server 2003") {
Get-WmiObject -ComputerName $Server.Name -Class win32_logicaldisk | Where-Object {$_.deviceid -match "C"} |
ft $server.name, $server.operatingsystem, deviceid, freespace, size -AutoSize }#Out-File -Append $2003LogPath }
}
(Get-WmiObject -Class Win32_Product -ComputerName $PCNumber -ErrorAction SilentlyContinue | Where-Object { $_.Name -match "$softwareName" }).Uninstall() | Out-Null
I have following code which works perfectly. The only problem is that I wont to know if the software has been removed or not.This doesn't tells me but the code below does.
This way works for me.
$software = Get-WmiObject -Class Win32_Product -ComputerName $PCNumber -ErrorAction SilentlyContinue | Where-Object { $_.Name -match "$softwareName" }
$soft = $software.Uninstall();
$n = $software.ReturnValue;
if ( $n -eq 0 ){
SOFTWARE HAS BEEN REMOVED.
}
my question is that how do i tell if the software has been removed or not.
using this code.
(Get-WmiObject -Class Win32_Product -ComputerName $PCNumber -ErrorAction SilentlyContinue | Where-Object { $_.Name -match "$softwareName" }).Uninstall() | Out-Null
You have to check the ReturnValue property. When you pipe to Out-Null you are suppressing the output of the operation and there's no way to tell what happened, unless you issue a second call to find if it returns the software in question.
I recommend using the Filter parameter (instead of using Where-Object) to query the software on the server. To be safe you should also pipe the results to the Foreach-Object cmdlet, you never know how many software objects you get back due to the match operation (and you call the Uninstall method as if the result is one object only):
Get-WmiObject -Class Win32_Product -ComputerName $PCNumber -Filter "Name LIKE '%$softwareName%'" | Foreach-Object {
Write-Host "Uninstalling: $($_.Name)"
$rv = $_.Uninstall().ReturnValue
if($rv -eq 0)
{
"$($_.Name) uninstalled successfully"
} # Changed this round bracket to a squigly one to prperly close the scriptblock for "if"
else
{
"There was an error ($rv) uninstalling $($_.Name)"
}
}