Istredd6669
Istredd6669

Reputation: 21

How to get the username of the person who is currently logged in and use it further?

I apologize for the title, it doesn't say much. Please, just take a look at my script

$env:UserName
$FolderPath = C:\Users\UserCurrentlyLoggedIn\Desktop\5.1.0

# Function for the pop up message
function PopUp
{
Add-Type -AssemblyName System.Windows.Forms
$global:balmsg = New-Object System.Windows.Forms.NotifyIcon
$path = (Get-Process -id $pid).Path
$balmsg.Icon = [System.Drawing.Icon]::ExtractAssociatedIcon($path)
$balmsg.BalloonTipIcon = [System.Windows.Forms.ToolTipIcon]::Warning
$balmsg.BalloonTipText = ‘Back up directories have reached maximum capacity!'
$balmsg.BalloonTipTitle = "Files may not be backed up!"
$balmsg.Visible = $true
$balmsg.ShowBalloonTip(100)
}

if ((((gci -path $FolderPath -Recurse | Measure-Object -Property Length -Sum -ErrorAction Stop).Sum/ 1MB),2) -gt 110.00)
{
 PopUp
 } Else {
 'Size of folders is alright'
 }

So, what I want to achieve with this hell of a mess, is basically: Script has to check the size of few folders located under C:\Users\UserCurentlyLoggedIn and if the size of those folder is bigger than (currently 110MB), then the PopUp message has to be shown. Otherwise, it has to do nothing. Overall it works if I provide the exact path to folders, however I would like to put it (the script) with GPO for Organization Unit, so I'm looking for the way to put the username of the person who is currently logged in on the machine at the time when the script is going to be run, in the place of "UserCurrentlyLoggedIn".

Again, I apologize for my gibberish explanation. I'm kind of new to scripting and stuff, and I have even a hard time explaining right what I want to do.

I appreciate all the help!

Upvotes: 2

Views: 4080

Answers (2)

briantist
briantist

Reputation: 47832

You should not hardcode the path to the profile based on username because:

  • The default path for profiles may have been changed and not be in C:\Users
  • A system in another language may use different text for Users for example
  • A profile does not have to be in the default path in the first place
  • A profile may not use the user name itself, or it may be decorated with the computer name, the domain name, or other extra characters (like in the case of a local user and a domain user having the same user name, and both having a profile on the computer)

So instead, you can use %USERPROFILE% as the environment variable:

$FolderPath = "$env:USERPROFILE\Desktop\5.1.0"

Upvotes: 1

Clint Oliveira
Clint Oliveira

Reputation: 702

try replacing your 2nd line with

$FolderPath = "C:\Users\$($env:USERNAME)\Desktop\5.1.0"

you will always get the current users username. enter image description here

Upvotes: 2

Related Questions