Forum Discussion
Sept Win10 Update breaks PowerShell script
OK, I tried your suggested steps.
For the Username, $usrName.gettype() was a system object, not a string.
So I added a pipe to | Out-String, and it does convert $usrName to a string, but
prepends a newline.
So, for example, if $upath = "C:\Users", and $usrName is Bill, and then I try to do a
$usrPath = join-path -path $upath -ChildPath $usrName
instead of the expected C:\Users\Bill, I instead get
C:\Users
Bill
Do you know how I get rid of that extra newline? The latest version of PowerShell will
not accept -NoNewLine after | Out-String
Let me demonstrate the problem another way. Take this snippet of code;
#-----------
$usrName = Get-WmiObject -Class Win32_Process -Filter "Name = 'explorer.exe'" |
ForEach-Object { $_.GetOwner() | % { "$($_.User)" } } |
Sort-Object -Unique | Out-String
write-host "Logged in User is: " -NoNewLine
write-host ($usrName)
#----------
and run it in PowerShell. The printed username should be right after the
write-host "Logged in User is: " -NoNewLine
but it is not. Instead, it always prints the username on the next line
AFTER write-host "Logged in User is: " -NoNewLine
Any ideas on what changed in the last few weeks of win updates?
Neal
To share and try to help others that find this thread:
No one offered any real solution. So in the end, I stopped trying to use:
$usrName = Get-WmiObject -Class Win32_Process -Filter "Name = 'explorer.exe'" |
ForEach-Object { $_.GetOwner() | % { "$($_.User)" } } |
Sort-Object -Unique | Out-String
to get the logged in username, and instead switched to the following code, which works fine,
provided the output as a string, and did not have the extra newline like the Out-String command:
# Get current user
$CurrentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
# Set the variable to the first string before the "\" character
$CurrentDomainName = $CurrentUser.split("\")[0]
# Set the variable to the second string after the "\" character
$CurrentUserName = $CurrentUser.split("\")[1]
write-host "Logged in User is: " -NoNewLine
write-host ($CurrentUserName)
$upath = "C:\Users"
$usrPath = join-path -path $upath -ChildPath $CurrentUserName
write-host "Logged in User PathName is: " -NoNewLine
write-host ($usrPath)
The above works just fine.
Neal
- farismalaebSep 22, 2020Iron Contributor
if the main requirement is to get the username, why dont you try
$env:USERNAME
it's an environment variable which is applicable everywhere
$usrName = $env:USERNAME
write-host "Logged in User is: " -NoNewLine
write-host ($usrName)