Powershell script: read an AD attribute and set is an environment variable - powershell

I have a problem with some old apps and I need to set an environment variable from AD (hurray)
I'm quite new to PS scripting, so I can use some help.
In my AD I have filled the attribute departmentNumber with information, that part works fine.
Now I need to create a logon script which reads this field from the current user (attribute: departmentNumber, derived from: inetOrgPersonUser) and set this as an environment variable called AFDELING.
I know this can be done using a VB script, but I prefer PS. Can anyone help me with this one?
Thanks in advance for your help,
Peter

Working with environment variables in PowerShell involves the special variable $Env and unfortunately you need to use a .NET method to set environment variables as no cmdlet exists (at least as of v2):
[Environment]::SetEnvironmentVariable("AFDELING", "DeptNo", "User")
The first string parameter is the variable name, the second is the value and the third is basically the persistance level requested for the variable: Machine, User or Process - both machine and user will survive a reboot and future applications will have access to them, though you will need to be running PowerShell with an administrative account to modify the machine-level variables.
Getting the user info should be equally easy. There are a variety of ways that you can access Active Directory, though one of the simplest in your case would be to use the System.DirectoryServices.DirectoryEntry class:
$de = New-Object System.DirectoryServices.DirectoryEntry
$DeptNo = $de.Properties["departmentNumber"]
That should query the current user record from a domain controller, and assign the value from the departmentNumber attribute to the $DeptNo variable. You can then just pop that variable into the second parameter from the first example.

Related

How to trigger RegenerateUserEnvironment forcibly

I'm currently having trouble applying logon script(powershell) on windows servers.
The logon script has the line to set user environment variables but the variables don't look like being applying immediately from the result of set command on command prompts.
I've been looking at the behavior through process monitor while logging on to the new session.
And finally I have found the newly created variables need to be associated with RegenerateUserEnvironment function on shell32.dll.
I'm able to look at the correct result of set command after RegenerateUserEnvironment is called.
So I was wondering whether we had a way to trigger RegenerateUserEnvironment function and it needs to be executed on powershell.
Can you shed some light on this?
Best Regards,
Haewon

Using global variables in a ps1

I can't seem to find good enough solution to my problem. Is there a good way of grouping variables in some kind of file so that multiple scripts could access them?
I've been doing some work with Desired State Configuration but the work that needs to be done cannot be efficiently implemented that way. The point is to install Azure Build Agent on a server and then to configure it. There are some variables that really should not be inside a script file just copypasted like Personal Access Token. I just want to be able to easily change it without the need to go inside every script that would be using it. In DSC you can just make a .psd1 file and access the variables like for example AllNodes.NodeName. The config file invocation and parameters look like this:
.\config.cmd --unattended --url $myUrl --auth PAT --token $myToken --pool default --agent "$env:COMPUTERNAME" --acceptTeeEula --work $workDir'
I want to make the variable $myToken accessible from outside file for better security and having a centralized place from where I can change values. $myUrl is also important to have access to due to it changing with new update to Build Agent.
Thank you in advance for your effort. If anything is not clear please let me know.
I have two very different answers to your question, although either one of them may miss your point.
First, it's possible to define veriables inside your profile script. Most people only use the profile script to define a library of functions or classes. But a variable can be made global the same way.
I have a variable named $myps that identifies the folder where I keep my PS scripts (in subfolders).
When I start a session I generally switch to this directory (oops, I called it a folder above.
The second way involde storing values of variables in a CSV file, while the names are stored in the CSV header.i then have a quickie little comandlet that steps through a CSV file, record by record, generating different expansions of a template each time through.
These values are not quite global, but they can be used in more than one context.
Thank you for the help. Those are very useful solutions in some cases, but I dug a bit deeper and found solution that suits my purpose. Basically if you have a psd1 file suited for DSC use you can also access its content via normal ps1 file. For example:
NonNodeData =
#{
Pat = 'somePAT'
}
Let's say this section of a psd1 file called ENV.psd1 is on your local machine in C:/Configuration
To access the content of this file you have to make a variable inside your script and use Import-PowerShellDataFile like so:
$configData = Import-PowerShellDataFile -Path "C:\Configuration\ENV.psd1"
And now you are free to use anything stored inside ENV.psd1. For example if I want to extract my PAT from config file to be able to store it in a variable in the script:
$myPat = $configData.NonNodeData.Pat
Thanks to that I can just pass $myPat as a parameter when invoking config.cmd like so:
.\config.cmd --unattended --auth PAT --token $myPat
Keeping my code cleaner and easier for any future updates.

Can I enable / Disable an Azure Service Bus Topic using Powershell

I have spent a couple of hours search for a solution to disable my Azure Service Bus Topics using Powershell.
The background for this is we want to force a manual failover to our other region.
Obviously I could click in the Portal:
but I want to have a script to do this.
Here is my current attempt:
Any help would be great.
Assuming you're sure your $topic contains the full description, modify the status parameter in the array and then splat it back using the UpdateTopic method. I'm afraid I can't test this at present.
$topic.Status = "Disabled"
$topicdesc = $NamespaceManager.UpdateTopic($topic)
I don't think you'll need to set the entity type for the Status, nor do you require semi-colons after each line of code in your loop.
References
PowerShell Service Bus creation sample script (which this appears to be based off): https://blogs.msdn.microsoft.com/paolos/2014/12/02/how-to-create-service-bus-queues-topics-and-subscriptions-using-a-powershell-script/
UpdateTopic method: https://msdn.microsoft.com/en-us/library/azure/microsoft.servicebus.namespacemanager.updatetopic.aspx
Additional note: please don't screenshot the code - paste it in. I'd rather copy-and-paste than type things out.

Create event log entry with powershell and fill in user

I need to create entry to Windows Event Log (e.g. application log). I know how to do all the stuff beside filling in the user who performed the action.
Example:
I need to create a script, that writes some message into application log. I used this tutorial, which worked fine: http://blogs.technet.com/b/heyscriptingguy/archive/2013/06/20/how-to-use-powershell-to-write-to-event-logs.aspx
But I am not able to influence the "user". When adding entry in windows log, it always fills "User: N/A".
Any idea how to pass "user" argument to the "write-eventlog" cmdlet?
Thank you for your help.
Even though (as far as I'm aware) Write-EventLog does not provide an option to write directly to the "User" field, you have two workarounds:
Use built-in standalone exec "EventCreate.exe" (type in eventcreate /? to see the manual)
This one does support providing the username field. I'm not sure, but it may require a password for that user too.
Second workaround would be to pass $env:USERNAME to the "message" field of Write-EventLog. This way you will still obtain the environment's current user.
I hope that helped.

exchange powershell : get-user has no Description property?

When I run get-user|get-member in powershell with the exchange add-in I noticed there is no description property.
Does anyone know if it has been renamed to something else or another way of accessing it?
If you aren't looking to change the description this should work:
[PS] C:\>$ANR = "testuser#example.com"
[PS] C:\>$foo = [adsi]("LDAP://" + (get-user $ANR).DistinguishedName)
[PS] C:\>$foo.description
My Description
If you are wanting to edit, you will need to get further into System.DirectoryServices & look at how to write objects back to AD. It would likely be simpler to use quest of another package that does some wrapping. If you want to roll your own there are gobs of blogs on AD programming in Powershell.
Exchange itself provides minimal interaction with AD - essentially, it gives you some AD stuff because AD and Exchange are so connected, but it doesn't try to expose all of AD's functionality.
Check out quest.com/powershell; that is an add-in library (it's free), and it has a cmdlet called Get-QADUser which will get you what you need - somewhat more easily, and in a more PowerShell-ish fashion, than using ADSI (which is also completely legit for what you're after).
get-user? do you mean get-qaduser from the quest cmdlet suite?
if so, I believe not all properties are retrieved by default. There's an -Include parameter that lets you specify additional properties to retrieve from AD, IIRC.
It works on the console; however in the CSV file, it keeps appending
System.DirectoryServices.PropertyValueCollection
to the end of each line instead of the value
When I run it on the prompt by typing out the distinguishedname, the ldap query works..
$tmp =adsi
$tmp.description
bill
any ideas?
solved it.. its just $tmp.description.value