Check whatever input you have for the $Hostname
variable for extra characters, such as a newline `n
. When you type it out, it may not give you an error and work because it doesn't have to process things like that.
Powershell query works in prompt, but not in script
-
07-03-2022 - |
Question
I am trying to make a script that takes input of a hostname and tells me the current logged on user. It works when I run the command one by one on the powershell prompt (as an admin), but doesn't produce the expected output when I run the actual script itself.
Here is the relevant code:
$Row.Hostname = $Hostname
$getwmiobject = Get-WmiObject -class Win32_computersystem -computername $Hostname
$Username = $Getwmiobject.username
if($UserName -eq $NULL) {
$Row.Username = "No Current Logged on User"
}
else {$Row.Username = $Username
}
$csvfile += $Row
$csvfile |sort-object Hostname | Export-Csv "foo.csv
When ran in the command line, I get the correct user. When ran as a script, I get "No Current logged on user". I have no clue why this is happening.
EDIT: I suppose it's important to mention that I have the output writing out to a file, made the changes in the code above.
La solution
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow