Why is the output not showing here? - powershell

So I have an odd powershell issue that I'm not sure about here, perhaps someone with more experience than me can advise?
Basically I'm searching servers for any Services & Scheduled Tasks that are not Microsoft, then checking config files for a certain name....
The code used is slightly older because some of the servers are 2008 & powershell hasn't been updated on them (long story involving ransomware)..
If I separate the code, I get the expected results, but if I combine the code, some of the output is missing....
#$ErrorActionPreference = "SilentlyContinue"
Write-Host "********* Server: $env:computername *********"
Function RunSearch() {
$searchWords = "user1","user2"
Foreach ($sw in $searchWords)
{
Write-Host "********* Searching: C Drive for: $sw *********"
Get-Childitem -Path "C:\" -Recurse -Force -Include "*.ini","*.config","*.js","*.bat","*.xml" |
Select-String -Pattern "$sw" |
Select Path,LineNumber
}
Write-Host "********* Finished Searching: $env:computername *********"
}
Function RunGetTasksSrv() {
Get-WmiObject Win32_Service | ? {$_.StartName -notlike "*localsystem*" -and $_.StartName -notlike "" -and $_.StartName -notlike "*sql_*" -and $_.StartName -notlike "NT Authority\*" -and $_.StartName -notlike "NT Service\*"} | Select Name, StartName | ft -Auto
$schtask = schtasks.exe /query /s localhost /V /FO CSV | ConvertFrom-Csv | Where-Object {$_.TaskPath -notlike "*microsoft*" -and $_.Author -notlike "*microsoft*"} | Select TaskName,"Run As User"
$schtask | where { $_."Run As User" -ne "SYSTEM" -and $_."Run As User" -ne "NETWORK SERVICE" -and $_."Run As User" -ne "INTERACTIVE" -and $_."Run As User" -ne "LOCAL SERVICE" -and $_."Run As User" -ne "Run As User" -and $_."Run As User" -notlike "*User*"}
}
RunGetTasksSrv
RunSearch
Now if I rem out #RunSearch - in the output, there will be included:
TaskName Run As User
-------- -----------
But if I unrem it out, that bit is missing (along with users listed below)...
If I take out the functions & run it as one script, again the TaskName is missing.... i.e.
Write-Host "********* Server: $env:computername *********"
Get-WmiObject Win32_Service | ? {$_.StartName -notlike "*localsystem*" -and $_.StartName -notlike "" -and $_.StartName -notlike "*sql_*" -and $_.StartName -notlike "NT Authority\*" -and $_.StartName -notlike "NT Service\*"} | Select Name, StartName | ft -Auto
$schtask = schtasks.exe /query /s localhost /V /FO CSV | ConvertFrom-Csv | Where-Object {$_.TaskPath -notlike "*microsoft*" -and $_.Author -notlike "*microsoft*"} | Select TaskName,"Run As User"
$schtask | where { $_."Run As User" -ne "SYSTEM" -and $_."Run As User" -ne "NETWORK SERVICE" -and $_."Run As User" -ne "INTERACTIVE" -and $_."Run As User" -ne "LOCAL SERVICE" -and $_."Run As User" -ne "Run As User" -and $_."Run As User" -notlike "*User*"}
$searchWords = "user1","user2"
Foreach ($sw in $searchWords)
{
Write-Host "********* Searching: C Drive for: $sw *********"
Get-Childitem -Path "C:\" -Recurse -Force -Include "*.ini","*.config","*.js","*.bat","*.xml" |
Select-String -Pattern "$sw" |
Select Path,LineNumber
}
Write-Host "********* Finished Searching: $env:computername *********"
It's really odd & I can't see why that bit is being left out....
Is it likely just because powershell is so old on one of the affected servers?
$psversiontable
Name Value
---- -----
CLRVersion 2.0.50727.8762
BuildVersion 6.1.7601.17514
PSVersion 2.0
WSManStackVersion 2.0
PSCompatibleVersions {1.0, 2.0}
SerializationVersion 1.1.0.1
PSRemotingProtocolVersion 2.1
Any advice welcomed!
Thanks

I happened to have an old 2008 VM and was able to test this. Try adding -and $_.HostName -notlike "HostName" like this to the line below. I got no hits because of the -notlike filters you have but that's likely because MS didn't have as many tasks running under the user context back then, especially on servers. Adding that last -notlike strips out the headers for the nested tasks in other folders.
$schtask = schtasks.exe /query /s localhost /V /FO CSV | ConvertFrom-Csv | Where-Object {$_.TaskPath -notlike "*microsoft*" -and $_.Author -notlike "*microsoft*" -and $_.HostName -notlike "HostName"} | Select TaskName,"Run As User"

Related

Filter file "yyyy-MM-dd_HH-mm-ss_Computername_Username_File.json" by Computername/Username

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

Exchange 2010 Powershell - Return Users With SendAs Permissions But Filter Disabled Users

so I have a script that works fine that I found online and changed to suit my needs. I have pasted this script below. However, in the output there is a lot of disabled users that have permissions to the mailboxes. E.g. I'd get an Output like "Mailbox Name^Mailbox#email.com^ActiveUser ActiveUser DisabledUser" So I am wondering if there is a way to make the script skip disabled users, same way how it leaves out self permissions.
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010
. $env:ExchangeInstallPath\bin\RemoteExchange.ps1
Connect-ExchangeServer -auto
$OutFile = “C:\Send_As_Permissions.txt”
“DisplayName” + “^” + “Email Address” + “^” + “Send As” | Out-File $OutFile -Force
$Mailboxes = Get-Mailbox -resultsize unlimited | Select Identity, Alias, DisplayName, DistinguishedName, WindowsEmailAddress
ForEach ($Mailbox in $Mailboxes) {
$SendAs = Get-ADPermission $Mailbox.identity | where {($_.ExtendedRights -like “*Send-As*”) -and -not ($_.User -like “NT AUTHORITY\SELF”) -and -not ($_.User -like “s-1-5-21*”)} | % {$_.User}
$Mailbox.DisplayName + “^” + $Mailbox.WindowsEmailAddress + “^” + $SendAs | Out-File $OutFile -Append
}
If you want to report on enabled mailboxes only, filter the output from Get-Mailbox on the IsMailboxEnabled property:
$Mailboxes = Get-Mailbox -resultsize unlimited | Where-Object { $_.IsMailboxEnabled } | Select ...
If you want to report on individual rights assignments for enabled accounts only, you'll have to query AD based on the value of the User property you extract:
$SendAs = Get-ADPermission $Mailbox.identity | where {($_.ExtendedRights -like “*Send-As*”) -and -not ($_.User -like “NT AUTHORITY\SELF”) -and -not ($_.User -like “s-1-5-21*”)} | % {$_.User}
$domain,$username = $SendAs.Split('\')
$ADUser = Get-ADUser -Identity $username -Server $domain
if($ADUser.Enabled){
# output to report
}

Powershell to display all automatic services that are stopped and attempt to start those services

I want to create a PS script where it will display all the automatic services that are stopped, and will attempt to start the services afterward.
Below is the PS code. It is successfully displayed all the stopped services on remote server.
Get-WmiObject Win32_Service -ComputerName SERVER1, SERVER2 |`
where {($_.startmode -like "*auto*") -and `
($_.state -notlike "*running*") -and `
($_.name -notlike "gupdate") -and `
($_.name -notlike "remoteregistry") -and `
($_.name -notlike "sppsvc") -and `
($_.name -notlike "lltdsvc") -and `
($_.name -notlike "KDService") -and `
($_.name -notlike "wuauserv")
}|`
select DisplayName,Name,StartMode,State,PSComputerName|ft -AutoSize
You can simply store the results of your query into a variable instead of selecting and displaying it, and you'd have a bunch of win32_Service instances that all have a StartService() method. It's generally a good idea to check the docs of the wmi classes you're using, most of them have methods that act on the object being represented, instead of having to pipe them around to other cmdlets like most Powershell objects:
Win32_Service class methods
You'd use it like this:
$services = Get-WmiObject Win32_Service -ComputerName SERVER1, SERVER2 |`
where {($_.startmode -like "*auto*") -and `
# [...]
}
$service | select DisplayName,Name,StartMode,State,PSComputerName|ft -AutoSize
$Service | ForEach {$_.StartService()}
Consider also using Get-Service unless you have a requirement for using WMI. You have a couple differences but the idea is the same:
$Services = Get-Service -ComputerName SERVER1,SERVER2 |`
where {($_.StartType -eq "Automatic") -and `
($_.Status -notlike "*running*") -and `
($_.Name -notlike "gupdate") -and `
# ...
}
$Services | select Description,Name,StartType,Status,MachineName |ft -AutoSize
$Services | Start-Service
Also, you could also simplify your filter a lot by using the -notin operator:
where {($_.startmode -like "*auto*") -and `
($_.state -notlike "*running*") -and `
($_.name -notin "gupdate","remoteregistry","sppsvc","lltdsvc","KDService","wuauserv")
}

Empty element not allowed [duplicate]

This question already has answers here:
pipes and foreach loops
(2 answers)
pipe foreach loop CSV PowerShell
(3 answers)
Closed 4 years ago.
I can't seem to export anything into CSV. I did some browsing and reading, but having hard time converting my script.
$allmailbox = Get-Mailbox -ResultSize 20
foreach ($Mailbox in $allmailbox) {
Get-MailboxFolderPermission -Identity ($mailbox.alias+':\calendar') |
Where {
$_.User -like "Anonymous" -and
$_.AccessRights -ne "None" -or
$_.User -like "Default" -and
$_.AccessRights -ne "None" -or
$_.User -like "Default" -and
$_.AccessRights -ne "AvailabilityOnly"
} |
select Identity, User, AccessRights
} | Export-Csv C:\CSVs\calstest.csv
The empty element not allowed is referring to the | at the end of your foreach. The way that your loop is structured does not allow the pipe. Below shows a different approach that can work.
Below should get you everything in one CSV file:
Get-Mailbox -ResultSize 20 | foreach {Get-MailboxFolderPermission -Identity $($_.Alias+":\calendar") | Where {$_.User -like "Anonymous" -and $_.AccessRights -ne "None" -or $_.User -like "Default" -and $_.AccessRights -ne "None" -or $_.User -like "Default" -and $_.AccessRights -ne "AvailabilityOnly"}| select Identity,User,AccessRights} | Export-Csv C:\CSVs\calstest.csv -NoTypeInformation
I tested this without the Where-Object and it exported successfully. If you are not receiving any information you might want look more into your Where . Start with one condition and increase as needed.
$allmailbox = Get-Mailbox -ResultSize 20
Foreach ($Mailbox in $allmailbox){Get-MailboxFolderPermission –Identity ($mailbox.alias+':\calendar') |
Where {
($_.User -like "Anonymous" -and $_.AccessRights -ne "None") -or
($_.User -like "Default" -and $_.AccessRights -ne "None") -or
($_.User -like "Default" -and $_.AccessRights -ne "AvailabilityOnly")
}| select Identity,User,AccessRights} | Export-CSV C:\CSVs\calstest.csv
If that's what you're looking for, though you'll have to add backticks I think for it to be seen as a complete query
This works:
$allmailbox = Get-Mailbox -ResultSize 500
$result = Foreach ($Mailbox in $allmailbox){Get-MailboxFolderPermission –Identity ($mailbox.alias+':\calendar') | Where {$_.User -like "Anonymous" -and $_.AccessRights -ne "None" -or $_.User -like "Default" -and $_.AccessRights -ne "None" -or $_.User -like "Default" -and $_.AccessRights -ne "AvailabilityOnly"} | select Identity,User,AccessRights}
$result | Export-CSV C:\CSVs\calstest.csv -NoType

Combine multiple foreach results into a single report

$results = foreach ($Mailbox in (Get-Mailbox -ResultSize Unlimited))
{
get-MailboxFolderPermission -identity "$($Mailbox.Name):\Calendar" -ErrorAction SilentlyContinue |
Where-Object {$_.User -notlike "Default" -and
$_.User -notlike "Anonymous" -and
$_.AccessRights -notlike "None" -and
$_.AccessRights } |
Select #{N="Mailbox";E={$Mailbox.SamAccountName}}, FolderName, User, AccessRights
}
$results
I am still learning powershell (only 1 full year of experience). I'm using this code to report on calendar permissions for all end user mailboxes in our environment. The code works well but it only reports on the Calendar object. I need to run three separate reports to get the Calendar, Contacts, and Inbox permissions.
I have tried creating an array but it throws multiple values all on one line. (Some end users have more than one person with access to their Calendar/Contacts/Inbox. Does anyone have a good idea of how to combine these results?
thanks
Here is an example of what results I would like:
Iterating Mailboxes only once with an additional
ForEach ($Folder in 'Contents','Calendar','Inbox')
Should be more efficient:
#Date
$date = (Get-Date -f yyyy-MM-dd)
#Pull Permissions
$Permissions = ForEach ($Mailbox in (Get-Mailbox -ResultSize Unlimited )) {
ForEach ($Folder in 'Contents','Calendar','Inbox'){
Get-MailboxFolderPermission -identity "$($Mailbox.Name):\$($Folder)" -ErrorAction SilentlyContinue |
Where-Object {$_.User -notlike "Default" -and $_.User -notlike "Anonymous" -and $_.AccessRights -notlike "None" -and $_.AccessRights } |
Select #{N="Mailbox";E={$Mailbox.SamAccountName}},
#{N="Folder";E={$_.FolderName}},
#{N="User With Access";E={$_.User}},
#{N="Access";E={$_.AccessRights}}
}
}
#Export to Desktop
$Permissions | Sort User | Export-Csv "$env:USERPROFILE\Desktop\ExchangePermissions-$Date.csv" -NoTypeInformation
#Date
$date = (Get-Date -f yyyy-MM-dd)
#Pull Permissions
$Permissions = ForEach ($Mailbox in (Get-Mailbox -ResultSize Unlimited )) {
$userInfo = get-user $Mailbox.name | select Title
ForEach ($Folder in 'Contacts','Calendar','Inbox'){
Get-MailboxFolderPermission -identity "$($Mailbox.Name):\$($Folder)" -ErrorAction SilentlyContinue |
Where-Object {$_.User -notlike "Default" -and $_.User -notlike "Anonymous" -and $_.AccessRights -notlike "None" -and $_.AccessRights } |
Select #{N="Mailbox";E={$Mailbox.SamAccountName}},
#{N="Office";E={$Mailbox.Office}},
#{N="Title";E={$userInfo.Title}},
#{N="Folder";E={$_.FolderName}},
#{N="User With Access";E={$_.User}},
#{N="Access";E={$_.AccessRights}}
}
}
#Export to Desktop
$Permissions | Sort User | Export-Csv
"$env:USERPROFILE\Desktop\ExchangePermissions-$Date.csv" -NoTypeInformation