I am trying to figure out how to get correct numbers while checking size of user profiles.
While executing this code remotely, I get wrong numbers.
Invoke-Command -ComputerName $Server -Credential $credentials
-ScriptBlock {
$colItems = Get-ChildItem C:\Users | Where-Object {$_.PSIsContainer
-eq $true} | Sort-Object foreach ($i in $colItems) {
$subFolderItems = Get-ChildItem $i.FullName -recurse -force -ErrorAction Ignore | Where-Object {$_.PSIsContainer -eq $false} | Measure-Object -property Length -sum | Select-Object Sum
$i.FullName + " -- " + "{0:N2}" -f ($subFolderItems.sum / 1MB) + " MB" }
}
This gives me numbers like: C:\Users\admin -- 673.42 MB but when I run the same code locally it says 47.9 MB which is the true value.
Can anyone give me a tip or explain why is that. Thanks
$Server has the server name which I am passing earlier in the script. Everything works except the correct output from the code above.
Related
I have a folder containing text-files with a standardized naming-scheme like:
2021-03-16_21-25-55_Client1_Edward.Hall_ServerResponse.json
2021-03-16_21-25-33_Client2_Eloise.Glover_ServerResponse.json
2021-03-16_21-17-38_Client3_Millie.Walsh_ServerResponse.json
2021-03-16_21-17-30_Client4_Lilly.Morton_ServerResponse.json
2021-03-16_21-15-45_Client5_Tia.Curtis_ServerResponse.json
2021-03-16_21-15-23_Client1_Edward.Hall_ServerResponse.json
2021-03-16_21-15-10_Client1_Lilly.Morton_ServerResponse.json
2021-03-16_21-15-03_Client2_Eloise.Glover_ServerResponse.json
2021-03-16_21-12-14_Client2_Eloise.Glover_ServerResponse.json
2021-03-16_21-11-25_Client3_Administrator_ServerResponse.json
I want to filter the files and retrieve the latest file (LastWriteTime) of a specific Computername-/Username-combination. Therefore I want to use a code like this:
# $env:COMPUTERNAME = "Client1"
# $env:USERNAME = "Edward.Hall"
$MyFolder = "C:\MyFolder"
Get-ChildItem -Path $MyFolder -File -ErrorAction SilentlyContinue | Where-Object {
$_.Extension -eq ".json" -and $_.COMPUTERNAME -eq $env:COMPUTERNAME -and $_.USERNAME -eq $env:USERNAME
} | Sort-Object -Descending -Property LastWriteTime | Select-Object -First 1
Of course the part -and $_.COMPUTERNAME -eq $env:COMPUTERNAME -and $_.USERNAME -eq $env:USERNAME is NOT working and should only show up the direction to what I imagine.
In the example above the result should be the file "2021-03-16_21-25-55_Client1_Edward.Hall_ServerResponse.json".
I was thinking of using -match, but it should be a exact match -eq.
Could you please help me to find a solution for this?
Thank you very much!
As long as you can count on the name format always conforming to that standard you can just split up the name strings for your required sections:
# $env:COMPUTERNAME = "Client1"
# $env:USERNAME = "Edward.Hall"
$MyFolder = "C:\MyFolder"
Get-ChildItem -Path $MyFolder -File -ErrorAction SilentlyContinue | Where-Object {
($_.Extension -eq ".json") -and ($_.Name.Split('_')[2] -eq $env:COMPUTERNAME) -and ($_.Name.Split('_')[3] -match $env:USERNAME)
} | Sort-Object -Descending -Property LastWriteTime | Select-Object -First 1
I'm trying to find old files on my servers and having a little trouble with the drive path for the Get-NeglectedFiles function. My serverpath keeps showing up as \server\ .
Function Get-NeglectedFiles
{
Param([string[]]$path,
[int]$numberDays)
$cutOffDate = (Get-Date).AddDays(-$numberDays)
Get-ChildItem -Path $path -Recurse |
Where-Object {$_.LastAccessTime -le $cutOffDate}
}
$Endresults = #()
$serverlist = get-content "C:\temp\serverlist.txt"
foreach($server in $serverlist) {
$results = Get-WmiObject -ComputerName $Server -Class Win32_Share | select name
$Endresults += New-Object psobject -Property #{
Servername = $server
Result = $results
}
}
foreach($drive in $server){
$drives = $results | Where-Object { $_ -ne $null}
$serverpath = "\\" + $server + "\" + $drives + "\"
}
{Get-NeglectedFiles -path $serverpath -numberDays 90 | select name, lastaccesstime
}
You're probably looking to do something like this (I've simplified it a bit but you can extend on it):
$serverlist = Get-Content 'C:\temp\serverlist.txt';
foreach ($server in $serverlist) {
$drives = Get-WmiObject -ComputerName $Server -Class Win32_Share;
foreach ($drive in $drives.Name) {
$serverpath = "\\$server\$drive\";
$serverpath;
Get-NeglectedFiles -path $serverpath -numberDays 90 | select Name, LastAccessTime;
};
};
Explanation:
Get list of server names from file serverlist.txt
For each server in that list:
Retrieve the list of share names on that server
For each share on that server generate a serverpath and run Get-NeglectedFiles
Side note:
You also should probably inspect what is being returned by:
Get-WmiObject -ComputerName $Server -Class Win32_Share
And make sure that all of the shares returned are ones you want to use. For example, when I run it, I get shares like IPC$, print$, ADMIN$, as well as the default drive shares, and all other custom shares that have been created on the server. You probably aren't going to be cleaning files out of those.
Another side note:
You might want to consider using the -File parameter inside of your Get-NeglectedFiles command so that you are only targeting files and not directories.
new to Powershell and scripting, so here it goes. I'm trying to go through a list of pc's to pull out any Java exception sites (eventually I will query AD for all my workstations). The exception.sites file is located in each user profile \AppData\LocalLow\Sun\Java\Deployment\security folder. I'm not sure why I'm only pulling the sites from my workstation though.
$comps = Get-Content \\server1\users\james\test\comps.txt
$addPath = "\AppData\LocalLow\Sun\Java\Deployment\security"
$userprofiles = Get-WmiObject win32_userprofile -filter "LocalPath Like '%\\Users\\%'" | Select-Object -ExpandProperty Localpath | foreach {$_ + $addpath}
foreach ($pc in $comps)
{foreach ($profile in $userprofiles)
{if ((test-path "$profile\exception.sites") -ne $false)
{get-content -path "$profile\exception.sites" | Out-File \\server2\packages\java\siteexceptions\SiteExceptions.txt -Append
}
}
}
you need to make a couple of adjustments to the code.
Get-WmiObject has a -computername parameter which will make it run on a remote computer. Also you will need to move the WMi query inside the computer loop so that the query is run once on each computer that you are iterating.
Note: Since the destination points to a location within another user's profile, you will need administrator privileges to be able to traverse the protected path.
foreach ($pc in $comps)
{
$userprofiles = Get-WmiObject win32_userprofile -filter "LocalPath Like '%\\Users\\%'" -ComputerName $pc
foreach ($profile in $userprofiles)
{
$drive = (Split-Path -Path $profile.localpath -Qualifier) -replace ':','$'
$Remotepath = "\\$pc\$drive" + (Split-Path -Path $profile.localpath -NoQualifier) + $addPath + '\exception.sites'
if (test-path $Remotepath)
{
get-content -path $Remotepath | Out-File \\server2\packages\java\siteexceptions\SiteExceptions.txt -Append
}
}
}
recently I took it upon myself to learn Powershell. It was a rough 2 weeks and a lot of reading but I'm getting better and better. I had some pressure at work to help with correcting our CMDB. We are about 7 months away from having a true Depolyment/Asset Management system in place. We have many reasons for relying on Powershell right now and we're trying to clean up a mess before we get the management system in. Anyway, I created a script that gets a lot of information for us. We have about 3000 objects/pcs and we need as much info as possible. Anyway, I created a script. So far it works well but I wanted some opinions from the experts or any advice. I feel like I did a decent job putting this together with only 2 weeks experiance but I really want to know what others think.
One thing I noticed: Windows 7 Boxes with IE9 and Up do not return a value for IE Version. Anyone know why?
Please see my code below:
Set-QADPSSnapinSettings -defaultSizeLimit 0
$FullPCList = (Get-QADComputer -SearchRoot $ou | Sort Name | select -expand name)
foreach ($computer in $FullPCList) {
ping -n 2 $computer >$null
if($lastexitcode -eq 0) { $Online = "Yes" } else { $Online = "No" }
$PCInfo = (Get-WmiObject -ComputerName $computer -Class Win32_ComputerSystem -ErrorAction SilentlyContinue)
$WinInfo = (Get-WmiObject -ComputerName $computer -Class Win32_OperatingSystem -ErrorAction SilentlyContinue)
$ram = ((Get-WmiObject -ComputerName $computer -Class Win32_PhysicalMemory -ErrorAction SilentlyContinue | Measure-Object Capacity -Sum).Sum / 1MB)
$bios = (Get-WmiObject -ComputerName $computer -Class Win32_Bios -ErrorAction SilentlyContinue)
$ie = (Get-Wmiobject -ComputerName $computer -namespace “root\CIMV2\Applications\MicrosoftIE” -query “select version from MicrosoftIE_Summary” -ErrorAction SilentlyContinue)
$freespace = ((Get-WmiObject -ComputerName $computer -Class Win32_LogicalDisk | Select Freespace | Measure-object Freespace -Sum).Sum / 1GB)
#Start uptime check
$LastBootUpTime = $WinInfo.ConvertToDateTime($WinInfo.LastBootUpTime)
$Time = (Get-Date) - $LastBootUpTime
$formattime = '{0:00}:{1:00}:{2:00}' -f $Time.Days, $Time.Hours, $Time.Minutes
#End Uptime Check
if ($WinInfo.Caption -match "Windows 7") {
$name = (Get-ChildItem -Path "\\$Computer\C$\Users" -Exclude "*Service*","*admin*","*Public*","*ffodero*","*jgalli*","*jwalters*","*frochet*" | Sort-Object LastAccessTime -Descending | Select-Object Name -First 1).Name
$loggedintime = (Get-ChildItem -Path "\\$Computer\C$\Users" -Exclude "*Service*","*admin*","*Public*","*ffodero*","*jgalli*" | Sort-Object LastAccessTime -Descending | Select-Object LastAccessTime -First 1).LastAccessTime
}
if ($WinInfo.Caption -match "Windows XP") {
$name = (Get-ChildItem -Path "\\$Computer\C$\Documents and Settings" -Exclude "*Service*","*admin*","*Public*" | Sort-Object LastAccessTime -Descending | Select-Object Name -First 1).Name
$loggedintime = (Get-ChildItem -Path "\\$Computer\C$\Documents and Settings" -Exclude "*Service*","*admin*","*Public*" | Sort-Object LastAccessTime -Descending | Select-Object LastAccessTime -First 1).LastAccessTime
}
$table = #{
Model = $PCInfo.Model
IEVersion = $ie.Version
Serial = $Bios.SerialNumber
Memory = $ram
DriveFreeSpaceGB = $freespace
Manufacturer = $PCInfo.Manufacturer
OSName = $WinInfo.Caption
Computer = $computer
Uptime = $formattime
LastloggedinUser = $name
LastLoggedinDate = $loggedintime
LoggedOnDuringScan = $PCInfo.Username
ServicePack = $WinInfo.ServicePackMajorVersion
Online = $Online
}
New-Object PSObject -Property $table | Export-Csv C:\logs\mother.csv -NoTypeInformation -Append
}
The namespace root\CIMV2\Applications\MicrosoftIE has been removed starting with Windows Vista (see note at the end of the blog post). You should be able to read the version number from the registry, though:
$hive = [UInt32]'0x80000002'
$key = 'SOFTWARE\Microsoft\Internet Explorer'
$reg = [WMIClass]"\\$computer\root\default:StdRegProv"
$ieVersion = $reg.GetStringValue($hive, $key, 'Version').sValue
I'm looking to calculate the total size of all shared folders (except admin shares) on a number of different servers (consolidating all accessed files to a NAS box for easier backup / restore) but am having a bit of trouble finding a solution.
I'm certain this could be done in powershell but I just can't find the right information to get me going, I can currently spit out a list of all shares on the servers but am not sure where to go from here:
$servers =#(
"server1",
"server2")
foreach($server in $servers)
{
get-WmiObject Win32_Share -computerName $server -filter "Type = 0"
}
I would try to use Get-ChildItem to list the files and Measure-Object to count the sizes
$servers = #("server1", "server2")
$sizes = #()
foreach($server in $servers) {
write-host "Server: $server"
$serverSizes = #(gwmi -class Win32_Share -ComputerName $server -filter "Type = 0" |
% {
write-host " share: $($_.Name)"
$s = gci \\$server\$($_.Name) -recurse -force | Measure-Object -Property length -Sum
New-Object PSObject -property #{Name=$_.Name; Server=$server; TotalSize=$s.Sum }
})
if ($serverSizes) {
$totalServerSize = $serverSizes | Measure-Object -Property TotalSize -Sum
$serverSizes += New-Object PSObject -property #{Name="__Total__"; Server=$server; TotalSize=$totalServerSize.Sum }
$sizes += $serverSizes
}
}
Then you can e.g. select the total sizes like this:
$sizes |
? { $_.Name -eq '__Total__' } |
Select-Object Server,#{L='Size in MB'; E={$_.TotalSize/1mb}},#{L='Size in GB'; E={$_.TotalSize/1gb}}