PowerShell Script to pop up at logoff - powershell

I have a basic understanding of PowerShell.
I would like to get my hands on a PowerShell script that will run at logoff.
This script needs to warn a user that their USB storage device is still plugged in before they sign out and they have to acknowledge the fact that it is and then select ok and then proceed to sign out
I know that the script needs to placed in an accessible location with the correct permissions and that a GPO can be used to enforce this. The script part is what I need help with..
If anyone out there in the interwebs please help?
Environment OS: Windows 10
AD not in use. Novell system used.

After you checked out what Franco stated, you can try something like the following. But still need to figure out how to make it work properly:
$usbs = GET-WMIOBJECT win32_diskdrive | Where { $_.InterfaceType –eq ‘USB’ }
$devices = #()
foreach($usb in $usbs){
$devices += $usb.Model + ". "
}
$input = [System.Windows.MessageBox]::Show("There are USB devices connected, $($devices | Out-String) Would you like to proceed logging off?","Warning","YesNoCancel","Error")
if($input -eq "Yes"){
shutdown -L
}elseif($input -eq "No"){
shutdown -A
}else{
break
}
You will need to find a way to make the user input visible before the logoff screen.

Related

Powershell Script to reinstall Microsoft teams, Not able to find teams install

Currently I am trying to write a power shell script that will uninstall then install Microsoft Teams.
I have never written a power shell script before and I am having trouble having the script get the initial teams installation so I can uninstall it.
This is what I have written so far, I saw two ways of finding the teams install online and neither is able to find it so I am kinda lost, any help would be much appreciated.
(I know both are commented out I just did it like this for formatting in this question.)
Write-Host "-------------------------------------`n"
# Prompt for credentials
$credential = Get-Credential
$username = $credential.Username
$password = $credential.GetNetworkCredential().Password
Write-Host "Finding teams`n"
# Find teams 1
#$teamsapp = Get-AppxPackage -Name Microsoft.Teams
# Find teams 2
#$teamsapp = Get-WmiObject -Class Win32_Product | Where-Object { $_.Name -eq "Microsoft Teams" }
# Check if installed
if ($teamsapp) {
Write-Host "Microsoft Teams is installed."
} else {
Write-Host "Microsoft Teams is not installed."
}
`
Teams is a bit tricky because it installs per user, not per computer. Assuming you're running the script under the user's account, you can check the following registry location using Get-ChildItem:
Computer\HKEY_CURRENT_USER\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\Teams
This code worked for me:
Get-ChildItem -Path 'HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\' | Where-Object { $_.Name -like '*Teams' }
You should be able to use the "QuietUninstallString" property of the result to get the command needed to uninstall Teams.
As a side note, consider looking into the Teams Machine Wide Installer for deploying teams. It installs to the computer and runs at logon for each user to detect if Teams is installed to their AppData folder. If not, it installs it automatically. This lets you avoid having to run as the user or loop through all the users AppData folder to manipulate user apps.

Showing currently logged in user in a PowerShell running from a RMM Software as SYSTEM

i searched hours of my time and saw many ideas for this scenario but nothing worked for my like it should (i tested every code i saw on my own machine but nothing got me to the result i wanted.)
background: we are using a script in our RMM Software to Rename the Agents
$benutzer = [Environment]::UserName
Set-ItemProperty -Path "HKLM:\Software\MMSOFT Design\PC Monitor" -Name ComputerName -Value "$env:USERDOMAIN - $env:Computername - $benutzer"
This script gives us for the $env:USERNAME the user SYSTEM but we actually want the real USERNAME which is logged into this system.
Please help me out :)
The environment variable [System.Environment]::GetEnvironmentVariable('username') will give you the username for the executor of the script, in your case that is System because this is user who ran the code.
If you want to user the environment variable for the user, you must make it so the script been ran from or on behalf of the user, this also means that user must have "permissions" to modify the registry.
If I understand right, you need to know who is the "Logged in user" for the machine where that script runs, unfortunately there is nothing available from PowerShell that do that to my knowledge, instead you could use the build-in tool query for Windows machines, which will provide you with a list with all logged in users to that machine, you would need to further test it to get what you want from it, the output looks like this :
PS C:\Users\t-user> query user
USERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME
>t-user console 1 Active none 8/29/2022 11:58 AM
The trick with query user is that it will provide you with the list of users in case more than one have logged in.
I see what you are trying to do, and here is a "dirty" example of doing it :
$loggedUserList= query user
if($loggedUserList.count -eq 2){
$user = $loggedUserList -split ">" -replace '\s\s+', ';' | convertfrom-csv -Delimiter ';' | select -ExpandProperty username
Write-Host "Logged in user is - $user"
}else{
Write-Host "More than one user have signed"
}

Pass stored Credential variable to new script

I have successfully built a working simple program that displays a menu and allows a user to choose which script to open and it runs in the same window.
I would like to be able to store credentials so that you would only need to enter them once while using this program and it passes them through to other scripts.
Please can someone advise.
I played around and found a solution. Seems the variables are carried through the session regardless if it runs a new script.
This bit of code sorted it out.
if ($cred -eq $null)
{
try {
Write-Host "`r`n"
$cred = Get-Credential -Credential $username
}
catch {
Write-Host -ForegroundColor Red "`r`nSomething has gone wrong with entering credentials. Please try run the script again or if issues persist please contact the system administrator.`r`n"
Return-ExitRestart
}

Remotely Enable Wakeup from Shutdown

I am trying to get 400 pcs setup to wake on lan.
everything is enabled on all the pcs but one check box.
Under the advanced tab on the nic, "wakeup from Shutdown" is disabled
and I need to enable it on all pcs.
I have a working script to change the boxes under the power management tab but those are already checked. but I cant seem to find any info about anything under the advanced tab. properties on nic, configure, advanced)
Any help in figuring out if this is possible would be a big help.
Could I edit that code to just enable what I need? or simpler to write a new one?
I haven't tried anything cause I cant seem to find any info as to if this is even possible.
im thinking its just a different wmi object (probably wrong name) but in my code that works I found the lines that go to each check box and am wondering if there is a class for "wakeup from shutdown"
*** line im curious about
foreach ($NIC in $NICs) {
$Errors = $false
Write-Host "NIC:"$NIC.Name
#Allow the computer to turn off this device
Write-Host "Allow the computer to turn off this device....." -NoNewline
***$NICPowerManage = Get-WmiObject MSPower_DeviceEnable -Namespace root\wmi | Where-Object { $_.instancename -match [regex]::escape ($nic.PNPDeviceID) }
If ($NICPowerManage.Enable -ne $TurnOffDevice) {
$NICPowerManage.Enable = $TurnOffDevice
$HideOutput = $NICPowerManage.psbase.Put()
}
If ($NICPowerManage.Enable -eq $TurnOffDevice) {
Write-Host "Success" -ForegroundColor Yellow
} else {
Write-Host "Failed" -ForegroundColor Red
$Errors = $true
OTHER LINES
Get-WmiObject MSNdis_DeviceWakeOnMagicPacketOnly -Namespace root\wmi | Where-Object { $_.instancename -match [regex]::escape($nic.PNPDeviceID) }
I use this little tool called WMIExplorer.exe to navigate WMI. I think MSPower_DeviceWakeEnable is the class you are looking for.
After a few searches, I stumbled upon this. Perhaps that is similar to your problem.
https://www.itinsights.org/Enable-wake-on-lan-WOL-with-PowerShell/

Using Read-Host to output information from a script

I am trying to run a script against exchange to bring back all of the mailboxes a certain user has access to. I want to be able to input the usersname using read-host. I currently have this:
$username = Read-Host("Please enter users username")
#Enable Exchange cmdlets
add-pssnapin *exchange* -erroraction SilentlyContinue
Get-MailBox | Get-MailboxPermission -User $username | FL > C:\MailboxPermissions.txt
However, when I run this via powershell, it asks for the username, looks like it is starting to run the script, then powershell just exits and there is not data outputted
Any help would be greatly appreciated
Thanks for all the help
I finally figured it out and there were a couple of issues. It was to do with the result size. I added -resultsize unlimited:
$username = Read-Host("Please enter users username")
add-pssnapin *exchange* -erroraction SilentlyContinue
>Get-MailBox -resultsize unlimited | Get-MailboxPermission -User $username | FL > C:\MailboxPermissions.txt
It would also not work by running the .ps1 file as this was not run by admin, and it needs admin permissions to output to the location I want. Once I created a shortcut for it to run via the powershell.exe with admin credentials it is now working as expected.
The problem is that you are only out putting to the screen.
This means that when you run your script it will carry out the required action, print to screen and close the window immidiatly. In turn, this means you can't see the output.
As #DarkLite1 mentioned, you could output to a file.
Or, you could simply allow the console to wait before closing. This is done like this at the end of your code:
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
You may also need a Write-Host on the last action in your code snippet, I'm not entirely sure as I am not familiar with how Get-Mailbox works, but try it without first.
To summarize, You must keep the window open or print the results to file to actually see anything. The code you have currently will complete so fast you will never see any output.