Logging off from all servers in a domain - windows

Occasionally I forget to log off from a server or am disconnected through an error and I don't remember the name of the server. And my domain account starts getting periodically locked out, so I have to access logs on DC to find out which server(s) keep locking my account and log off from it/them. So I wanted to write to script in powershell that would log me off from all servers in a domain (with the exception of the server where I run the script on of course) without me needing to search which to log off from. This is what I have:
$ErrorActionPreference = "Silentlycontinue"
$Servers = (Get-ADComputer -Filter *).Name
$ScriptBlock = {
$Sessions = quser | ?{$_ -match $env:USERNAME}
if (($Sessions).Count -ge 1)
{
$SessionIDs = ($Sessions -split ' +')[2]
Write-Host "Found $(($SessionIDs).Count) user login(s) on $Server."
$SessionIDs | ForEach-Object
{
Write-Host "Logging off session [$($_)]..."
logoff $_
}
}
}
foreach ($Server in $Servers)
{
if ($Server -isnot $env:COMPUTERNAME)
{
Invoke-Command -ComputerName $Server -ScriptBlock {$ScriptBlock}
}
}
But when I launch the script, nothing happens. The script doesn't return any errors but doesn't log me off from any server, nor does it write any of the messages from Write-Host cmdlet, obviously. I noticed the $SessionIDs variable definition only returns ID of the first session. Usually this shouldn't be a problem, since it's unlikely I will have more than one session on a server, but I'd like to have this insurance. Can anyone tell me what's wrong in the script?

I notice a few things...
"First, I don't think quser | Where-Object {$_ -match $env:USERNAME} will ever return anything. The output of quser will not contain the hostname."
Try this for getting logon sessions:
$Sessions = (query user /server:$Env:ComputerName) -split "\n" -replace '\s\s+', ';' |
ConvertFrom-Csv -Delimiter ';'
Next, when you reference the $Server variable on the remote machine in your script block, it is out of scope. You would need to use $Using:Server in the script block.
Lastly, the -isnot operator doesn't compare value, it compares type. So in your last foreach, the if statement evaluates to "if type string is not type string" and will not run. Try -ne or -notlike instead.

Working with objects is much easier if you can just parse the output of QUser.exe. Given your scenario, here's my take on it:
$servers = (Get-ADComputer -Filter '*').Name.Where{$_ -ne $env:COMPUTERNAME}
foreach ($server in $servers)
{
if (-not ($quser = ((QUser.exe /server:$server) -replace '\s{20,39}',',,' -replace '\s{2,}',',' 2>&1) | Where-Object -FilterScript { $_ -match $env:USERNAME })) {
Continue
}
Write-Verbose -Message "$($quser.Count) session(s) found on $server." -Verbose
($quser.Trim() | ConvertFrom-Csv -Header 'USERNAME','SESSIONNAME','ID','STATE','IDLE TIME','LOGON TIME').foreach{
Write-Verbose -Message "Logging user [$($_.UserName)] off." -Verbose
LogOff.exe $_.ID /server:$server
}
}
Filtering should always happen before hand meaning, filter out your computer name on your first call to Get-ADComputer. Since you're using QUser.exe and LogOff.exe to begin with, I'd recommend the use of it all the way through since LogOff accepts an ID value that QUser outputs.
Next, placing the call to quser inside your if statement does two things in this case.
Filters for all users matching $ENV:UserName
Returns $true if anything is found, and $false if not found.
So, switching the results using -not will turn $false into $true allowing the execution of the code block which will just continue to the next server.
This in turn doesn't bother with the rest of the code and continues onto the next computer if no matching names were found.
The use of $quser inside the if statement is so you can save the results to it if more than one name is found; (..) allows this as it turns the variable assignment into an expression having the output pass through onto the pipeline where it is either empty, or not.
Finally, referencing the $quser variable we can convert the strings into objects piping to ConvertFrom-Csv. Only step left to do is iterate through each row and passing it over to LogOff to perform the actual logoff.
If you've noticed, the headers are manually-specified because it is filtered out by the Where-Object cmdlet. This is a better approach seeing as there could be "more than one" RDP Session, now you're just left with those sessions matching the name which can be saved to $quser, so no extra filtering is needed down the line.

So I modified the script this way and it works, sort of. It logs off account from servers, which is the main goal. There are still some glitches, like the message it sends from the first Write-Host doesn't give server's name, the message from second one gives a different value than it should (it gives [1] value after -split instead of [2] for some reason; but those are not really that important things, even though I will try to make at least the first message right) and $SessionIDs still gives only the first value, but usually you shouldn't have more than one RDP session per server. I've seen more sessions of one user, but that is very rare. But I'd also like to fix this if possible. Nevertheless, the script basically does the most important thing. But if someone has a suggestion how to fix the glitches I mentioned I would be grateful.
$ErrorActionPreference = "Silentlycontinue"
$Servers = (Get-ADComputer -Filter *).Name
$ScriptBlock = {
$Sessions = quser | ?{$_ -match $env:USERNAME}
if (($Sessions).Count -ge 1)
{
$SessionIDs = , ($Sessions -split ' +')[2]
Write-Host "Found $(($SessionIDs).Count) user login(s) on $Server."
Foreach ($SessionID in $SessionIDs)
{
Write-Host "Logging off session $SessionID..."
logoff $SessionID
}
}
}
foreach ($Server in $Servers)
{
if ($Server -ne $env:COMPUTERNAME)
{
Invoke-Command -ComputerName $Server -ScriptBlock $ScriptBlock
}
}

Related

The rights of the .exe of a windows service powershell

I am blocked with my code
I will try to explain what I would like to do with it,
my code is to scan the different windows services, to keep in memory only what uses an .exe and then to search among them the ones that the users have full control of.
I would like it to display the service and its rights at the end.
$services = Get-WmiObject win32_service | ?{$_.PathName -like '*.exe*'} | select Name, State, Pathname, StartName | Out-Null
foreach ($service in $services) {
$var = "{0}.exe" -f ($Service.PathName -Split ".exe")[0]
foreach ($right in $var ){
if ( (Get-Acl $var).Access -ccontains "BUILTIN\Utilisateurs FullControl "{
Write-Warning " Exploit detected "
}
}
}
thank you in advance for your feedback
Get-CimInstance Win32_Service |
Where-Object { $_.PathName -like '*.exe*'} |
Select-Object Name, State, Pathname, StartName |
ForEach-Object {
$_.PathName = ($_.PathName -split '(?<=\.exe\b)')[0].Trim('"')
Add-Member -PassThru -InputObject $_ Acl (Get-Acl -LiteralPath $_.PathName)
} |
Where-Object {
$_.Acl.Access.Where({
$_.IdentityReference -ceq 'BUILTIN\Utilisateurs' -and
$_.FileSystemRights -eq 'FullControl'
}, 'First').Count -gt 0
}
Note that 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) (v6+), where all future effort will go, doesn't even have them anymore. Note that WMI still underlies the CIM cmdlets, however. For more information, see this answer.
The above uses the ForEach-Object call to:
update the .PathName property of each object to contain only the - unquoted - path of the executable with each service.
add an .Acl property to each object via Add-Member, containing the service executable's ACL, obtained via Get-Acl.
The resulting list of objects is then filtered by those whose service-executable ACL contains an entry for identity BUILTIN\Utilisateurs[1] with full control over the executable.
That is, the resulting objects are effectively those for which you meant to issue Write-Warning " Exploit detected "
As for what you tried:
$services = ... | Out-Null by definition captures nothing[2] in variable $services, given that Out-Null's purpose is to suppress output.
While $var = "{0}.exe" -f ($Service.PathName -Split ".exe")[0] does extract the executable path (although .exe should be \.exe\b, for robustness), it may include enclosing double quotes, which should be stripped.
It's unclear where $rights comes from.
You cannot use -ccontains to match across multiple properties of an object, and note that the purpose of the -contains operator and its variants is to test presence of a value in full, in a collection, not to look for a substring in a single string.
[1] It's interesting to see that these identity references are localized; the equivalent on a US-English system would be BUILTIN\Users. Generally, it would be better to obtain a culture-independent representation of this identity, namely its SID, and use that for comparison: $_.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value -eq 'S-1-5-32-545'
[2] Loosely speaking, $null; technically, it is the singleton value that PowerShell uses to signal "no output received", [System.Management.Automation.Internal.AutomationNull]::Value.
If I begin by the begining you terminate your first line by | out-null so $services contains nothing.
Then you forgot a ")" in your if.
You should present your code with indentations.
Be carefull :
"{0}.exe" -f ("C:\WINDOWS\system32\msiexec.exe /V"-Split ".exe")[0]
Gives :
C:\WINDOWS\system32\ms.exe
So use a '\' before the '.' :
"{0}.exe" -f ("C:\WINDOWS\system32\msiexec.exe /V"-Split "\.exe")[0]
which gives (regular expression story ?):
C:\WINDOWS\system32\msiexec.exe
So it will give something like that.
$services = Get-WmiObject win32_service | ?{$_.PathName -like '*.exe*'} | select Name, State, Pathname, StartName
foreach ($service in $services) {
$var = "{0}.exe" -f ($Service.PathName -Split "\.exe")[0]
if ((Get-Acl $var.Trim('"') -ErrorAction Stop) -ccontains "BUILTIN\Utilisateurs FullControl "){
Write-Warning " Exploit detected "
}
}

How to get one property and output from a child job?

I have a child job in a file test.ps1:
param($unit)
$p = $unit
Start-Job -Name $unit -ScriptBlock {
param($p)
"Hallo $p"
New-Object PSCustomObject -Property #{
Not_found = "agurk"
}
} -ArgumentList $p
When I do:
PS> .\test 2
PS> $a=Get-Job|Receive-Job |Select-Object -Property Not_found
I unfortunately get
PS> $a.count
2
Why 2 and not 1?
And I have to do
PS> $a[1].Not_found
agurk
in order to get the value.
I want to create a child job which produces some output, and one property and only one for the caller to investigate. How can I achieve that?
You're getting a count of 2 because your job returns the string "Hallo 2" and your custom object #{Not_found="agurk"}. From the documentation:
In Windows PowerShell®, the results of each statement are returned as output, even without a statement that contains the Return keyword.
The Select-Object doesn't skip over or remove that string, instead it creates a new custom object with an empty property Not_found, so you end up with a result like this:
[
{ 'Not_found': '' },
{ 'Not_found': 'agurk' }
]
If you don't want the string output to be captured, change this line:
"Hallo $p"
into this:
Write-Host "Hallo $p"
Or don't create undesired output in the first place.
If the additional output is desired and you need to be able to redirect it separately from the returned object you can't use Write-Host, though, since that cmdlet writes directly to the host console (meaning its output cannot be captured or redirected). Instead you need to write to a different stream, e.g. the verbose stream:
Write-Verbose "Hallo $p"
Note that you need PowerShell v3 or newer to be able to redirect streams other than the Success and Error streams.
The count of two comes from the fact the job returns two lines of output, "Hallo $p" and the object.
Because you're doing an unconditional select, it seems Powershell is returning objects whether or not the property exists.
You could change your query to check whether or not the property is populated by using a Where-Object:
$a = Get-Job | Receive-Job | Where-Object { $_.Not_Found -match ".+" }
Then access with $a.Not_Found
Alternatively, directly accessing the property from your result also seems to only return non-empty values:
$a = $(Get-Job | Receive-Job | Select-Object -Property Not_Found).Not_Found

Powershell - Variables and foreach loop

This thread got me started very well, but now I need more help
I am trying to loop through my serverlist.txt file, and pass the results of Get-EventLog to Out-GridView and then on to a .csv file. I have this working, but I have to select all the records in the GridView window then click OK for each server.
So, I have the idea that I want to create a $sys variable outside the loop, go in, append the results to that variable for each server, and then exit the loop and pass $sys over to Grid-view.
My confusion comes regardinf variable declaration, type, appending and placement in the code...
I'm just learning PS now, so this may be a little basic for you :)
this code works...need to add in the variable idea in the right places:
#Drop the existing files
Remove-Item C:\system.csv
# SERVER LIST PROPERTIES
# Get computer list to check disk space. This is just a plain text file with the servers listed out.
$computers = Get-Content "C:\ServerList.txt";
#Declare $sys here ??
# QUERY COMPUTER SYSTEM EVENT LOG
foreach($computer in $computers)
{
if(Test-Connection $computer -Quiet -Count 1)
{
Try {
# $sys =
Get-EventLog -ComputerName $computer -LogName System -EntryType "Error","Warning" -After (Get-Date).Adddays(-7) `
| Select-Object -Property machineName, EntryType, EventID, Source, TimeGenerated, Message `
| Out-GridView -PassThru | Export-Csv C:\System.csv -NoTypeInformation -Append;
}
Catch
{
Write-Verbose "Error $($error[0]) encountered when attempting to get events from $computer"
}
}
else {
Write-Verbose "Failed to connect to $computer"
}
}
# $sys | Out-GridView....etc.
Thanks!
Kevin3NF
Just to close this out, I used suggestions from mutiple comments:
$sys = #() (outside the loop)
$sys += Get-EventLog (inside the loop)
$sys | Export-Csv (after the loop to send to .csv)
I even blogged the whole thing, including all the various iterations of learning I went through:
http://dallasdbas.com/getting-to-know-powershell-from-an-old-dba/
Thanks to all that helped. This gave me a framework I will continue to use on these servers as the needs arise.
Kevin3NF

Powershell 'Optimize-Volume' Output

I have written a system maintenance script which executes basic functions that retrieve statistics from a host, writes the output to a new PSObject, then finally combines the results and converts it all to a HTML web page.
I do not seem to be able to write the output of Optimize-Volume to the pipeline, I have to use -verbose - why is this? I would like to check the results of the Optimize-Volume cmdlet by looking for the following text which is generated at the end of the -verbose output, depending on the result:-
'It is recommended that you defragment this volume.'
'You do not need to defragment this volume.'
Here is the function:-
function Get-DefragInfo {
$getwmi = Get-WmiObject -Class Win32_volume -Filter "DriveType = 3" | Where-Object {$_.DriveLetter -cne $null} -ErrorAction SilentlyContinue
$letter = $getwmi.DriveLetter -replace ':'
foreach ($drive in $getwmi)
{
$analysis = Optimize-Volume -DriveLetter $letter -Analyze
if ($analysis -like 'It is recommended that you defragment this volume.')
{
$props =[ordered]#{‘Drive Letter’=$letter
'Defrag Recommended?'='Yes'}
}
elseif ($analysis -like 'You do not need to defragment this volume.')
{
$props =#{‘Drive Letter’=$letter
'Defrag Recommended?'='No'}
}
$obj = New-Object -TypeName PSObject -Property $props
Write-Output $obj
}
}
How do I capture the output I need?
Thanks in advance.
In PowerShell 3.0 and onward, you can use the stream redirection operator > to capture the Verbose ouput to a variable:
# Merge stream 4 (Verbose) into standard Output stream
$analysis = &{Optimize-Volume -DriveLetter $letter -Analyze -Verbose} 4>&1
# Check the "Message" property of the very last VerboseRecord in the output
if($analysis[-1].Message -like "*It is recommended*")
{
# defrag
}
else
{
# don't defrag
}
If we Get-Help Optimize-Volume -full we'll see the cmdlet has no output.
Some searching lead me to this Microsoft Scripting Guys article that pointed out using the following to check if Defrag is needed.
(gwmi -Class win32_volume -Filter "DriveLetter = 'C:'").DefragAnalysis()
Knowing this, we can easily make an IF Statement.
$DefragCheck = (gwmi -Class win32_volume -Filter "DriveLetter = 'C:'").DefragAnalysis() |
Select DefragRecommended
IF($DefragCheck){"Defrag recommended"}ELSE{"Defrag is not needed."}
It's helpful to pipe cmdlets to Get-Member in order to see if there are any options available. In the above example, we can pipe gwmi -Class win32_volume -Filter "DriveLetter = 'C:'" to Get-Member and find the DefragAnalysis method, which we use dotted notation to access (wrap the Get-WmiObject in () then use a . and the method name followed by (), it looks confusing until you try it a couple times!)
Thanks, I went for the verbose redirection option and it seems to be working well. My method is not the cleanest way of doing it I understand, but it works for me.
I like the second option also, I'm going to look at using this once the script is complete and functionality is proofed.
Thanks for your help once again.

Breaking foreach loop in PowerShell v2

I'm having trouble terminating a foreach-object loop in PowerShell v2. For a rough idea of the task I'm trying to accomplish, here's the pseudo-code:
Read lists of host machines from a text file
For each host in the text file get Win32_Product (filtered against an exclusion list),
convert output to html and save.
The reason for the script is that I've amassed a text file listing all applications included on standard client images, and would like to periodically scan hosts from another text file to see if there are any unauthorized, sketchy or otherwise unnecessary applications on the host machines.
The code does work in a rough sense, but the main issue I'm having is that the script will not terminate without manual intervention. I guess the component I'm missing here is to run the loop until some condition exists (ie. first line in the host file is encountered for the second time), then terminates the script. Although this is the method I've envisioned, I am always open to other logic, especially if its more efficient.
Here's the actual code:
Get-Content c:\path\to\testhostlist.txt | Foreach-Object {
Get-WmiObject Win32_Product |
Where-Object { $_.Name -f "'C:\path\to\testauthapplist.txt'" |
ConvertTo-Html name,vendor,version -title $name -body "<H2>Unauthorized Applications.</H2>"}} |
Set-Content c:\path\to\unauthapplisttest.html
I don't see how the first line of the host file (I infer you mean testhostlist.tx) would ever be encountered a second time, since you're only listing it once. This doesn't even seem to be an infinite loop that would need an exit condition. Foreach-Object doesn't repeat indefinitely.
It seems to me that the problem is not that the loop doesn't exit without a condition, it's that the syntax is invalid.
Where-Object filters the pipeline by passing only objects that meet a certain condition, but the scriptblock that follows doesn't perform a boolean test.
In fact, the content of the scriptblock doesn't appear valid in and of itself. -f is the format operator, and takes a format string as the left operand, but $_.Name is not a format string.
I'm going to take a guess here, based on your description, that the idea is to filter the results of Get-WmiObject Win32_Product for objects whose Name property isn't listed in testauthapplist.txt (I take it that's the "exclusion list" you're referring to). If so, this is the correct syntax:
Get-Content c:\path\to\testhostlist.txt | %{
Get-WmiObject Win32_Product | ?{
(Get-Content 'C:\path\to\testauthapplist.txt') -notcontains $_.Name
} | ConvertTo-Html name,vendor,version -title $name -body "<H2>Unauthorized Applications.</H2>"
} | Set-Content c:\path\to\unauthapplisttest.html
(Note that %{} and ?{} are just abbreviations for Foreach-Object and Where-Object, respectively.)
If i understood you correctly you are trying to stop your Script completely? If so did you try Break?
If you only want to skip a loop use continue
$hostlist = Get-Content c:\path\to\testhostlist.txt
$a = #()
Foreach($item in $hostlist)
{
$a += "<style>"
$a += "BODY{background-color:gray;}"
$a += "TABLE{margin: auto;border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}"
$a += "TH{border-width: 1px;padding: 4px;border-style: solid;border-color: black;background-color:yellow}"
$a += "TD{border-width: 1px;padding: 4px;border-style: solid;border-color: black;background-color:white}"
$a += "h2{color:#fff;}"
$a += "</style>"
Get-WmiObject Win32_Product | select name,vendor,version | sort name | ConvertTo-Html -head $a -body "<Center><H2>Unauthorized Applications.</H2></Center>" | Out-File c:\path\to\$item"-applist.html"
}

Resources