How to output specific information from a powershell command? - powershell

So I've been playing around with Powershell recently, trying some things with a basic command net user $username. As an example net user administrator produces an output that you can see at the bottom of this page.
My question is: How do I output specific elements of this?
I'm aware of pipes and have been trying to use them but I think I'm missing something as it never comes out right. Lets say, for example, I just want user name, full name, password expires and last logon to be shown as an output. What command do I use after the pipe to get this?
Many thanks!

net.exe is not a PowerShell cmdlet. Therefore getting information out it is processing the output of the executable as a string.
For example, retrieving the user name:
$netoutput = net user administrator
#User name is on the first line, separated by spaces, the actual username is last word
$netoutput[1].Split(" ")[-1]
If you are using Win10 1607 or newer, you could retrieve this information with the Get-LocalUser cmdlet
Get-LocalUser administrator | Select-Object Name,FullName,PasswordExpires,LastLogon

Related

Force Powershell to create AD user folder when setting HomeDirectory value

During the New-ADUser command: -HomeDirectory = '\sharedrive\folder$%username%'
When this value is set in Powershell, the value appears as \\sharedrive\usersfolder$\%username% under the Home Directory.
Result:
However, if I manually enter that same string into the Active Directory Users and Computers menu and then hit apply, it autofills to the person's username where %username% exists and creates a folder on that share drive with proper permissions, shown below:
How can I get Powershell to autofill this username and create the folder? Just writing the string out with the user's name does not work.
I think there are a couple of problems here. PowerShell doesn't know how to interpret your input string '\sharedrive\folder$%username%'
For one, it is a literal string - so even if PowerShell knew that $%username% meant "convert this value to the username environment variable" it would still interpret it as the literal characters entered in the string. What you're appearing to try and do is string interpolation which requires that you use double quotes ".
Second, the %username% portion is not the way that you use environment variables in PowerShell. There are a few ways to get this value. $env:USERNAME should work on windows, so would [Environment]::username.
So you would want to do something like this "\sharedrive\folder$([Environment]::username)"
for a user 'someuser' this would return "\sharedrive\foldersomeuser"
You're confusing both environment variables AND how these values are set in ADUC and when using Powershell cmdlets.
%username% is a Windows environment variable which can be translated, thus when you hit the "Apply" button the ADUC console translates the username from the account you're creating, then in the background goes and creates that folder using the credentials of whoever is running ADUC, then (if you hit the "Yes" button) also repermissions it to give that user Full Control.
Once again its the ADUC which creates the folder for you, it doesn't happen just because you set those properties on the account object. If you want Powershell to do this then you need to carry out the folder creation and permissioning yourself, either manually or via more Powershell scripting.
Try something like this:
$NewUser = Read-Host "please enter a username"
New-ADUser -Name "$NewUser" -HomeDirectory "\sharedrive\folder\$NewUser"
Btw Efie is absolutely right about how environment variables are being passed, but the other thing is that those variables he mentioned will be the variables of whomever is running the script, not the user you are creating.

Get Memberships Of User

I have a very simple question but for some reason I can't seem to get my head around it.
I need a line of code that could be ran as a user from a client and lists all the "memeber of" groups from the AD (ONLY FOR THIS CURRENT USER). similar to
Get-ADGroupMember -identity "domain admins" -Recursive | foreach{ get-aduser $_} | select SamAccountName,objectclass,name
I would like the result to be listed.
I either need a way to import the AD module on a client computer or another way to contact the DC and get the users current "memeber of" groups.
/Niklas
I found the best way for my needs but CB.'s answer worked as well!
[ADSISEARCHER]"samaccountname=$($env:USERNAME)").Findone().Properties.memberof -replace '^CN=([^,]+).+$','$1'
I can then keep using this output in my code
you can use dos command line:
net user /domain %username%
The easiest way to do this would be with
Get-ADPrincipalGroupMembership -identity "Username"
Now this also means that you would have to have the active directory module loaded which you can find more information on its use on Technet Get-ADPrincipalGroupMember
If you simply want to produce a list, make a call to the command prompt as I find this works well, although it does truncate group names:
net user %username% /DOMAIN
If you want to programmatically get them and easily do something with that data, you'll want to rely on the Active Directory cmdlets.
To determine if you have these readily available in Powershell, you'll need to run the following command:
Get-Module –ListAvailable
If you don't see ActiveDirectory in the list you will need to first download and install the Windows Management Framework and import the module yourself:
Import-Module ActiveDirectory
Once that's done I believe this command should do the trick:
(Get-ADUser userName –Properties MemberOf | Select-Object MemberOf).MemberOf
Hopefully that gets you started. I'm fairly certain that there's more than one way to accomplish this with Powershell. Take a look at the Microsoft TechNet documentation to see if you can find something that better suits your needs.
Personally I have only ever needed to query AD group memberships ad-hoc for diagnostic purposes and have always relied on Get-ADUser or the command line call, depending on the target audience of the resulting data.

powershell get PID for specific app running for calling user

We have an ERP application with restrictive licensing, which we access via RemoteApp. We need to only allow one instance per user. So, I've been experimenting with PowerShell to try to do this.
What the script has to do is check and see if "pxxi.exe" is running for the calling user.
My first attempt used WMI. It worked, but it turns out WMI is very very slow.
(gwmi win32_process -Filter "name='pxxi.exe'" | ? {$_.getowner().user
-eq $env:username}).pid
My second attempt used Get-Process. This works great, but unfortunately requires elevated rights.
Get-Process pxxi -IncludeUserName | ? {$_.username -match $env:username}).id
My third attempt focused on the win32 command line program Tasklist.
$result = Invoke-Command { c:\windows\system32\tasklist.exe /fi
"username eq $env:username" /fi "imagename eq pxxi.exe"}
This works! And thanks to EBGreen's code, I can extract just the PID.
($result[3] -split '\s+')[1]
And while that runs really quick as an Administrator, for regular users, Tasklist runs as slow as WMI, above...
So, that puts me back to square one.
Does anyone out there know of a bit of code to quickly check and see if a user XYZ is running a process with name ABC.EXE ?? This needs to work for regular users (but regular users don't need to see other user's processes) and it needs to not take 30+ seconds to run.
I'm not married to powershell. VBScript would be fine. Or any little tool available on the internet.
Thanks!
For the example that you have:
($result[3] -split '\s+')[1]
Be aware that this works for just one result being returned. If you expect more than one instance then you should write a loop to iterate from the 4th item in the array on splitting each item to get that process's PID.
I gave up trying to find a way to do it in Powershell. Either the method was too slow, or required admin.
So I wrote something in C#:
c# - check if program is running for current user

How to format output in Posh Server (Powershell web server)?

I am currently trying the Powershell web server PoSH (http://poshserver.net/) for some administration reports. But i don't know how to format ouput.
From the start: i start the console with the default shortcut, with admin rights. I type Import-Module PoSHServer, then Start-PoSHServer. The web server starts, then i create a simple index.ps1 file, with just one line of code in the body section: $(command).
For example, i want to use the Get-Service Mpssvc command, but what i obtain is :
System.ServiceProcess.ServiceController
I try Get-Service MpsSvc | Select Name,Status. Output:
#{Name=MpsSvc; Status=Running}
Same thing for cmdlets Get-Process, i have an output with list of processes but it appears like this: System.Diagnostics.Process (AcroRd32) ...
However, some cmlets just like the Get-Date (used in the Posh demonstration web page) works fine and have a "normal" output.
I read the documentation, but there is no example which can help me for that.
How can i write powershell code to obtain a "clean" and console-like output?
I just downloaded and installed Posh-Server yesterday after reading this post.
If you want output to look like console inside a web-page you are probably looking at this from the wrong angle, you need to think string not console. Your code is supposed to be running inside of a here-string, in the example. So I got the hint here that the standard console formatter does not apply, posh-server will use whatever it wants to to turn your returned object into a STRING!. Your code output will get turned into a string using whatever formatter it deems applies unless you explicitly return a string - which the example script does correctly do. So try this on the console
get-process "power*" | out-string -width 80
And then try it in your posh-server script.
You probably really wanted this:
Get-Service MpsSvc | Select Name,Status | out-string -width 120
Hope that helps - I think the lack of examples in this project is a good thing because this is really a very simplistic web-server; lots of conceptual thinking required before you even start :) .

Displays the date of account expiration - Windows Server 2003

I'm using following command:
dsquery user -limit 0 | dsget user -display –samid –acctexpires –disabled
But I get this message
Value for 'Target object for this command' has incorrect format
What is the correct syntax?
I ran into these issues all the time. It is because the people that are creating objects in AD do not follow what Microsoft considers as standards for naming objects and placing objects properly. What I typically have to do to get around this is to break it up into pieces and work on it iteratively. For example above I would create a text file of just the DSQuery command by doing this:
DSQUERY user limit 0 > Results.txt
Now that you have all the user objects in a text file you can run the above command using:
Type Results.txt | Dsget user -display –samid –acctexpires –disabled > NewList.txt
By looking at the very bottom of Newlist.txt you can see that last "successful" record that was retrieved. Go back to the Results.txt file in Notepad and search for that record and look at the record below it. You will need to delete the record (or make a change in AD and start all over). If you delete the record just run the same DSGet command above and keep going until it runs all the way through with no errors.