Using Read-Host to output information from a script - powershell

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.

Related

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"
}

PowerShell Script to pop up at logoff

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.

Why does Enable-Mailbox show all mailbox properties when finished?

I have a Powershell script that creates AD Users from a CSV file and creates a mailbox in our on-premises Exchange server. The script works well, but every time it finishes the 'Enable-Mailbox' command, it outputs the mailbox properties as if 'Get-Mailbox | FL' is being called. The command is used as follows:
Enable-Mailbox -Identity <identity> -Alias <alias> -Database <database>
This link says that Enable-Mailbox has no output (https://learn.microsoft.com/en-us/exchange/client-developer/management/exchange-management-shell-cmdlet-input-and-output-types), and this command is at the end of the loop, so nothing else would be outputting anything before moving on to the next user.
Can anyone shed some light on what's going on or point me in the direction to figure out why this is happening?
EDIT: I'm piping to Out-Null to suppress the output for now

Check AD users' network share mapping with PowerShell

I tried using net use, net share, among others - none of which return the expected output. So instead, I'm modifying a script I found to see which network drives/shares are mapped to a user the script is pushed to. Then I go to my log file, look at the data, and determine if the account is set up properly. Here's the current script:
Get-WmiObject Win32_MappedLogicalDisk -computer $env:COMPUTERNAME | select name, providername
Out-File -filepath "\\*UNC filepath*\Mapped_Drives_$env:USERNAME$(get-date -Format _MM-dd-yy" # "HH.mm.ss" "tt).txt"
When I run it, the log file returns empty and I'm not sure why. I changed "Out-File -filepath" to "Start-Transcript" which isn't working the way I want it to either (with too much verbose output). It outputs fine in my PowerShell ISE with all the proper shares listed, but doesn't work when I navigate to the logged output. What am I missing?
You must pipe the output into the logfile
$logfile = "\\*UNC filepath*\Mapped_Drives_$env:USERNAME$(get-date -Format _MM-dd-yy" # "HH.mm.ss" "tt).txt"
Get-WmiObject Win32_MappedLogicalDisk | select name, providername | Out-File $logfile
On a more general note I'd use the commands to fix the mapped drives right there and then, instead of just writing them to a logfile for later inspection.

Running Command as Administrator from a SYSTEM Process

So I need to clear a user's run dialog history which I can do perfectly fine with "reg delete HKEY_CURRENT_USER\Software\Windows etc..." from an elevated powershell window on the logged in user's machine, but what I'm looking to do is that same command but from a SYSTEM powershell process. I have already used psexec to create a powershell window which runs as SYSTEM, but because you can't just use HKEY_CURRENT_USER as SYSTEM with the same results, I am finding it quite difficult. If I could just run that command but as username\Administrator then I wouldn't have this problem.
Also to note, if I can somehow grab the username of the logged on user (from SYSTEM still) in one line in plain text (with no other output in sight), then I can store the username in a variable and convert that to an SID and use HKEY_USERS instead.
P.S. Don't ask why I'm running powershell as SYSTEM, I know what I'm doing :D
you can use get-process under the system context powershell and filter where explorer.exe process is running, get the account it is running under then use to convert to SID and go through the registry.
something like this assuming only 1 explorer.exe process is running which is the norm on windows client OS.
$proc = Get-CimInstance Win32_Process -Filter "name = 'explorer.exe'"
$owner = Invoke-CimMethod -InputObject $proc -MethodName GetOwner
$username = $owner.user
$username will contain the user, $owner will also contain domain and a few other things.
to convert to sid
$objUser = New-Object System.Security.Principal.NTAccount($owner.Domain, $owner.User)
$strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
$strSID.Value