How to rename computer account using Powershell 2.0

Hi,
For my Win7 deployment environment i need a script that can rename my workstation and it's Active Directory computer account.
Is this possible using Powershell 2.0 included in Win7?

I created a PowerShell script that, among other things, renames the computer.
Function Rename-Computer ([string]$NewComputerName) {
$comp = (gwmi win32_computersystem).Name.Trim()
$ComputerInfo = Get-WmiObject -Class Win32_ComputerSystem
Write-Host "Renaming computer...`n`tOld name: $comp`n`tNew name: $apnewname"
#Start-Sleep (10)
$ComputerInfo.rename($NewComputerName) | Out-Null
After that you should reboot
function RestartMachine{
$os = gwmi win32_operatingsystem
$os.psbase.Scope.Options.EnablePrivileges = $True
$os.Reboot()
Or better yet just use the `Restart-Computer` cmdlet built into PoSH.
Now, the original post also said there was a need to rename the computer object n AD.  Below are two functions I use primarily for moving AD objects into their appropriate OU home.  While that doesn't immediately answer the question or solve the
problem, I do believe you can rename the object you bind to using a very similar method.
# This was created with the idea that machines would join the
# domain automatically, into a predetermined OU. From there,
# we would determine which OU the machine should be in, then
# move it by calling this function.
function MoveOU ($newOU) {
$comp = (gwmi win32_computersystem).Name.Trim()
$dumpOU = "CN=Computers,"
# DC=dc,DC=net
$root = [adsi]""
#CN=Computers,DC=dc,DC=net
$srcOU = [adsi]("LDAP://"+$dumpOU+$root.distinguishedName)
#OU=fixedOU,OU=testOU,DC=dc,DC=net
$destOU = [adsi]("LDAP://OU=fixedOU,OU=testOU,"+$root.distinguishedName)
#CN=COMPUTERNAME,CN=Computers,DC=dc,DC=net
$admin = [adsi]("LDAP://CN="+$comp+","+$srcOU.distinguishedName)
#$admin.psbase | get-member | where-object {$_.Name -eq "MoveTo"}
#System.Void MoveTo(DirectoryEntry newParent), System.Void MoveTo(DirectoryEntry newParent, String newName)
$admin.PSBase.MoveTo($destOU)
Function Move-OU ($SiteDC, $newOU) {
$computerName = (gwmi win32_computersystem).Name.Trim()
$_computerType = "CN=Computer,CN=Schema,CN=Configuration,DC=dc,DC=net"
$path = "LDAP://$SiteDC/DC=dc,DC=net"
$domain = "domain"
$user = "user"
$pass = "password"
$de = New-Object System.DirectoryServices.DirectoryEntry($path,"$domain\$user",$pass)
$ds = New-Object System.DirectoryServices.DirectorySearcher($de)
$ds.Filter = "(&(ObjectCategory=computer)(samaccountname=$computerName$))"
$res = $ds.FindAll()
if ($res.count -gt 0) {
# Machine has been found
# Bind to the Computer Object in AD
$oldComputerObject = New-Object System.DirectoryServices.DirectoryEntry($res[0].path,"$domain\$user",$pass)
#$oldOU = $oldComputerObject.distinguishedName
$oldOU = $oldComputerObject.Path
Else {
$strFilter = "(Name=$computerName)"
$objDomain = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$SiteDC/dc=dc,dc=net","$domain\$user",$pass)
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher($objdomain)
$objSearcher.SearchRoot = $objDomain
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = "Subtree"
$colPropList = "distinguishedName", "Name"
foreach ($i in $colPropList){$objSearcher.PropertiesToLoad.Add($i) | Out-Null}
$colResults = $objSearcher.FindAll()
#$colResults.Count
if($colResults.count -gt 0) {
foreach($result in $colResults) { $target = $result.Properties }
$Error.Clear()
#$oldOU = $target.distinguishedname
$oldOU = [string]$target.adspath
Else {
write-host "`tWARNING: Unable to locate $computername in AD; Cannot move to correct OU"
ErrorLog "WARNING: Cannot move object $computername to correct OU; Not found in AD."
$destOU = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$SiteDC/$newOU","$domain\$user",$pass)
$oldComputerObject.PSBase.MoveTo($destOU)
/\/\o\/\/ who has been known to dabble in scripting a bit (;) has also covered this subject here.  I would copy & paste, but I highly recommend reading it to get a better understanding of what's going on.  Plus, there's LOADS of useful information
on that site!
http://mow001.blogspot.com/2006/09/powershell-active-directory-part-11.html

Similar Messages

  • Add shared calendar to another users account using powershell

    Hi,
    I am trying to add a calendar to another using account using powershell as it will be easier to make a script than logging in to each user and adding the calendar. Has anyone done this before or know how to do it.
    Thanks

    Are you asking about Outlook or about Exchange?
    In Exchange you can likely do this via EWS.
    Here is how to do this in Access but has to be done under user account:\
    http://www.outlookcode.com/threads.aspx?forumid=2&messageid=27088
    Under EWS it is similar but can be done by impersonation.
    ¯\_(ツ)_/¯

  • How to verify my account using my yahoo email? and how to open my apple id in what mail in iphone 4?

    how to verify my account using my yahoo email? and how to open my apple id in what mail in iphone 4?

    Hi stanlaw,
    Welcome to the Support Communities!
    The information below should help you with this.
    Associating and verifying email addresses with your Apple ID
    http://support.apple.com/kb/HE68
    How to verify the primary email address for your Apple ID
    When you first create an Apple ID (using your email address) a verification email will be sent to that address. If you sign in to your Apple ID from the link in that email, the email address will be verified as the primary email address for your Apple ID. You can also resend the email verification if the email address is not verified:
    1. Sign in to My Apple ID to manage your account information.
    2. Click Resend under Primary Email Address.
    3. Verify your changes by following the link in the email you will receive from Apple and signing back in to your account.
    I hope this information helps ....
    Happy Holidays!
    - Judy

  • Home directory creation for local user accounts using powershell

    Through Computer Management when I create a user, a home directory is created for the same user in the folder C:\Users.I am creating a user through powershell in a remote machine.I am using the following script to create user 
    $comp = [ADSI]'WinNT://localhost,computer';
    $user = $comp.Create('User', 'account7');
    $user.SetPassword('Welcome1');
    $user.SetInfo();
    The account is getting created. But no home directory is created for this user. How to create a home directory for a user using powershell? Also the user created through GUI is a member of the group 'Users' by default. How to add the user created to the
    'Users'  Group.

    Hi Cmm user,
    Thanks for your posting.
    To set the attribute of homedirectory for a user in powershell, please also try the cmdlet set-aduser:
    import-module activedirectory
    $HomeDrive=’Z:’
    $UserRoot=’\\CONTOSO-FPS\Users$\’
    $HomeDirectory=$UserRoot+$AccountName
    SET-ADUSER $AccountName –HomeDrive $HomeDrive –HomeDirectory $HomeDirectory
    I hope this helps.
    We
    are trying to better understand customer views on social support experience, so your participation in this
    interview project would be greatly appreciated if you have time.
    Thanks for helping make community forums a great place.

  • How to change thecontract account using bapi can anybody provide the code

    How to change the contract account using BAPI_CTRACCONTRACTACCOUNT_CH1.
    pls reply.
    i will reward points .

    Hi Archana,
    The best way would be to read the BAPI documentation and check if they provided an example. If there is no example, test the BAPI in SE37 using your test data. Also, do not forget to call the 'BAPI_TRANSACTION_COMMIT' after the BAPI call (using test sequence in SE37).
    Regards,
    Shyam

  • How to rename my network; using Airport Extreme

    I would like to rename my wireless network and guest network. I am using Airport Extreme, and have extended the network using an Airport Express. Can someone tell me how to rename these, and what problems I might run into when I try to use Wi-Fi devices after I've done that?

    Welcome to the discussion area, Cindyluhu!
    You would use AirPort Utility to change the name of your wireless network. It will be relatively easy to change the name on the AirPort Extreme...4-5 clicks and Update
    In order to change the name on the Express, you'll need to "hard reset" it and reconfigure it. Not too difficult if you have done this before.
    If you change the name of the wireless network, you will need to enter the password to connect to the network the first time that you log on with any of your devices. If you have them set to "remember" the network, you won't have to enter the password again unless you make another change to the network name or password.
    Post back if you need some steps to change the wireless network name on your devices.

  • How to get specific accounts using ScriptedHostResourceAdapter

    Hi
    we are using ScriptedHostResourceAdapter for mainframe.
    But how to get some specific list of users.
    When i try to get the connetion using
    <invoke name='getAffinityConnection' class='com.waveset.adapter.HostConnPool'>
    Iam getting error. Though LoginAction is there in idm and working with users and reconciliations.
    com.waveset.exception.ItemNotFound: ResourceAction: LoginAction
    When i try to use listAllObjects still iam getting the same error.
    com.waveset.exception.ItemNotFound: ResourceAction: LoginAction
    <invoke name='listAllObjects'>
                   <new class='com.waveset.adapter.ScriptedHostResourceAdapter'>
                   <rule name='commonRuleLib:RUL_getWSObject'>
    <argument name='Id' value='Mainframe'/>
    <argument name='type' value='Resource'/>
    <argument name='context'>
    <invoke name='getAuthenticatedContext'>
                             <new class='com.waveset.server.InternalSession'/>
                             <s>configurator</s>
                        </invoke>
    </argument>
    </rule>
                        <new class='com.waveset.object.ObjectCache'/>
                   </new>
                   <s>Account</s>
                   <map>
                   <s>accountId</s>
                        <s>G1NXV6T</s>
                   </map>
                   <s>configurator</s>
                        <invoke name='getPassword'>
                             <invoke name='getObject' class='com.waveset.ui.FormUtil'>
                             <invoke name='getAuthenticatedContext'>
                                  <new class='com.waveset.server.InternalSession'/>
                                  <s>configurator</s>
                             </invoke>
                             <s>User</s>
                             <s>configurator</s>
                             </invoke>
                        </invoke>
              </invoke>
    Please help if any solution is there
    Thanks
    Edited by: shailu541 on Feb 3, 2010 10:50 AM
    Edited by: shailu541 on Feb 3, 2010 10:52 AM

    I think i got it now. iam not passing objectcache
    <invoke name='getCache'>               
                             <new class='com.waveset.server.InternalSession'/>                         
                   </invoke>

  • How to rename computer in os 10.8

    My late 2011 iMac somehow inherited the name of my previious computer - MacPro G5. How do I remane my curent computer to iMac new or something like that

    System Preferences->Sharing.
    Edit the Coumpuer Name: field

  • How to disable Guess Account using Apple Remote Desktop or command line

    The Guess Account is enabled with parental control for 900 iMacs. How can I disable the Guess account with ARD and commandline?

    After searching for a long time.
    The answer is:
    dscl . -create /Users/Guest UserShell /usr/bin/false

  • How Can This Computer Be Used Right Out Of The Box With NO WORD PROCESSING!

    I just want to know why I can't do homework on a $1099 laptop!

    Welcome to the discussions!
    As mentioned, virtually no PC comes with MS Office on it - and that's a good thing. Most people do not need all the features of Office in a standard home setting and including it would just increase their price needlessly. Students who turn in homework through email will usually need it since teachers really don't want to be bothered with multiple file formats. I can't blame them.
    Check out your school's bookstore. It is likely that they have Office for Mac at a great price. If not - or if you want a different program - use OpenOffice or Apple's own iWork.

  • How to purchase apple account using HDFC debit card from india

    Hi,
    I want purchase iOS developer programs using HDFC VISA debit card (India) it is possible?
    Please give me answer..
    Thanks in advance..

    Your best bet is to buy it from Amazon, or any other online retailer which services are available in Singapore, since Apple USA will not ship to Singapore...

  • How to stop computer from using microsoft outlook to send email link instead of thunderbird.

    Recently added microsoft security essentials as security when problem started.

    Try set [[Make Thunderbird the Default Mail Client|Thunderbird as default client email]].

  • Can`t rename computer computer account is already exists

    We have domain on 2 DC`s(1 is GC and the 2nd is DC(Server 2008r2 ent)), Sometimes we need to replace old computers to the new ones. But they have to to be named like the old ones. So sometimes after removing old comuter from the AD, we still have an error
    message "Can`t rename, computer account is already exists" where else should we remove it????????

    Let's try the following:
    - configure the other domain controller as a Global Catalog - this should be the case in a single-domain forest
    - force the garbage collection by following http://blogs.technet.com/b/ad/archive/2009/03/24/taking-out-the-trash.aspx
    Check the list of deleted objects again afterwards.
    If this does not provide the resolution, restore the tombstone of one of the deleted computers (followhttp://technet.microsoft.com/en-us/magazine/2007.09.tombstones.aspx ),
    rename it , and delete it
    hth
    Marcin
    i`ve tried all of that except, configuring other Dc as GC, i ve found an article http://technet.microsoft.com/en-us/library/cc737269(v=ws.10).aspx it
    says that nothing would happen if two DC`s will be GC`s, but it vad not been written that this article aplies to win2008r2 only to earliests OS`s, so i`m affraid if something wrong will happen if i will promote another DC to GC, or i`m wrong??!
    I couldn`t force garbage collection, but i`ve enabled log as you said, and it seems to be no trouble with it....
    about the restoring tombstone.... i ve stuck on the step when i should search the deleted object, because search result "getting 0 entries"
    The same thing is about the article that Sandesh Dubey had linked "http://technet.microsoft.com/en-us/library/dd379509(v=ws.10).aspx"
    if i am not wrong, i should go to Configuration in tree of ldp and then to the Deleted Objects, but it says that there is no children.
    Please people be patience with me, i really am need your help!

  • How to delete term using powershell?

    Hello
    I want to delete a particular term from termstore. I dont have termset name. Without termset name how can I delete term using powershell?
    Avi

    If you don't know the termset net it makes it tricky.
    In theory if you know the name of the term you could look through all termsets to find it. The catch of course is to ensure there is only one instance of the term otherwise you may delete terms you need.
    Which version of SharePoint?
    Jason Warren
    @jaspnwarren
    jasonwarren.ca
    habaneroconsulting.com/Insights

  • How to pass input arguments to Worker Role Application using Powershell

    Hi All,
    I have a worker role running in Windows Azure Portal. I need to pass arguments to this Worker role service and get the output by using PowerShell.
    Can someone please specify how this can be achieved using PowerShell?
    Thanks and Regards,
    Vivek

    Hi,
     Please refer to the Following StackOverflow article that talks about how to configure PAAS instances for Powershell remoting.
     http://stackoverflow.com/questions/15787768/accessing-azure-cloud-service-paas-instances-via-powershell-remoting
    Regards,
    Nithin Rathnakar

Maybe you are looking for

  • Purchase Order - Issue storage location set mandatory entry

    Hello All, When create subcontracting PO, want to set the field of Issue storage location as mandatory. I tried to find configuration "Materials Management>Purchasing>Purchase Order-->Define Screen Layout at Document Level", but there is not entry "I

  • Uninstalling iTunes. iPod 4 'ClickWheel' wont show up. Please HELP!

    Hi everyone. Ok here's my situation. Im using a MacBook Pro (Mac OS X Lion 10.7.5) iTunes 11.4 (64Bit) iPod 4th Gen. (White 20GB 'Click-Wheel') After doing a system restore on my ancient dinosaur ipod 4th gen. (the white 20GB 'Click Wheel') and 'upgr

  • Auto generated service PR from maint, order

    Dear Experts, As you know while processing external services using control key PM03, a service PR will be generated for the service selected from the agreement or contract & from there we will create PO. Here in my case while creating PO from auto ge

  • Logic Pro X interface freeze

    Just started having major issues with the LPX interface "partially" freezing up and becoming unresponsive: tracks disappear when I attempt to rearrange them, can't get the input track showing up in the mixer for new tracks, playhead doesn't move but

  • Dynamic calculation of diff. beween various months values

    The requirement is: If the users input values for calmonths say, may'05 to aug'05, then the query will be able to calculate net value for four months (i.e it should be able to create 4 columns) and the diffence calculations from may'05(net value) - a