Powershell dealing with a range of computer names.

Hello all.  Abridged description, I'm a lab admin trying to re-write a VBS login script into Powershell.  I need to be able to run commands determined by computer name and number...for instance, I have complabA01 through complabA70.  01-25
need to do an action and copy a shared file, 26-40 need a different action and the same shared file, and 41-70 get a different action still and said shared file.  I've got the base code laid out and functional to determine the computer name and specific
lines based on that:
$cn = $env:computername
If($cn -like 'complabA*'){do stuff}
If($cn -like 'complabB*'){do other stuff} so on. 
Is there a way go a layer deeper on that and say "if your number 01-25 do this"?  The problem well may be that I'm coming at this with slightly deeper roots in VBS... so I may well be over/under thinking this.
In case it'll help, in VBS we handle it by turning the numbers at the end of the name into a separate variable and using said secondary variable in a select case.
Any thoughts on how that can be done in Powershell?

You can do this using a regular expression match. For example:
$computerName = "complabB04"
$computerName | select-string '^complab([\D])([\d]+)' | foreach-object {
$labCode = $_.Matches[0].Groups[1].Value
$computerCode = $_.Matches[0].Groups[2].Value
"Lab code: $labCode" # B
"Computer code: $computerCode" # 04
-- Bill Stewart [Bill_Stewart]

Similar Messages

  • Powershell - dealing with {host1, host2, host3, ....}

    Hello,
    I'm working on a Clustered Windows 2012 R2 server, and I'd like to get the list the Preferred Owner list of some cluster Resources, but we have many nodes and the output is not readable from powershell because when use the standard command but it
    shows something like {server1, server2,.....} and the output on the screen is not complete.
    Then I've tried to get the output in table mode, but I don't know how to get it, I've used the following command using a "join" trick and I'm getting more or less what I want.
    get-clusterresource
    |
    Where{$_.resourcetype 
    -match
    "MyResourceType"}
    |
    get-clusterownernode | select clusterobject,,@{n='PrefOwners';e={$_.ownernodes
    -join","}}
    |ft-a
    I've got something like the following, all the Owners are included on a single column. I may survive with this, but I'll have to perform a second filter (excel) over  this output to split each PrefOwner in single columns.
    Resource Name                  PrefOwners
    "Cluster Resource name"    "PrefOwner1,PrefOwner2,PrefOwner3,prefOwner4,PrefOwner5"
    And I'd like to go an step further, what I want is have something like the following where each preferred owner has their own column.
    Resource Name                  owner1            owner2            
    Owner3           .......
    "Cluster Resource name"    "PrefOwner1"   "PrefOwner2"     "PrefOwner3"   .......
    How can I get this type of output on one single command?
    Best Regards
    Regards.

    And what's wrong with multiple commands?
    Your best bet would be to create a custom object with the columns you're after, but that involves iterating through each owner and you won't get it on a single command.
    However, bearing in mind that you're you're using Windows 2012 R2 which comes with PowerShell 4 and that you're quite keen on concise statements, there are things you can do to shorten your version so far (and make it faster! MOAR SPEED!)
    A quick example: since PowerShell v4 you can now invoke a .Where() method on collections. It runs faster than piping it to a Where-Object, does exactly the same thing, and the syntax is pretty much the same too. Here's an example:
    # New PowerShell v4 way, fastest
    (Get-Service).Where({$_.Name -eq 'spooler'})
    # PowerShell v3 way, faster than PS <v3 ways
    Get-Service | Where-Object Name -eq spooler
    # Notice I don't even need to put quotes around the service name, whereas on all the other methods I do. Talk about being lazy!
    # Old way... Slowest one
    Get-Service | Where-Object {$_.Name -eq 'spooler'}
    For comparison, I ran some tests on all 3 ways by invoking each way 10 times and using Measure-Command to capture the times
    The v4 way took 160ms~ to run.
    The v3 way took 350ms~ to run.
    The <v3 way took 450ms~ to run.
    I ran all tests multiple times with consistent results, so there you go!
    Now... as for your custom object, as I said you can't do it in a single call (unless you want to have all your code cluttered in a line with over 200 characters and expect someone to be able to read it - this is not code art (http://www.dalatdesigns.com/blog/?p=11678).
    Anyway, here's a method. I don't have any clusters, so I settled for reading the displaying each of the properties of a WMI instance as one per column, but you get the idea:
    # I *should* have used the -Filter parameter of Get-WmiObject here but am trying to get something as similar to your code as possible
    $Processes = (Get-WmiObject -Class Win32_Process).Where({$_.Name -eq 'PowerShell.exe'})
    #It is better not to use a pipeline here else you have no way of telling when the subproperties you're dealing with now are from the old object or the new one
    foreach ($Process in $Processes)
    $output = @{}
    $output.Name = $Process.Name
    # Normally it would work like this, but in WMI objects you can't retrieve them based on index, only name so... It should work for your objects though, give it a try!
    #for ($i = 0; $i -lt $Process.Properties.Count; $i++)
    #$output."Property$i" = $Process.Properties[$i].Name
    # As in this case we can't reference the property based on an index, we have to take another route...
    $i = 0
    foreach ($Property in $Process.Properties)
    $output."Property$i" = $Property.Name
    $i++
    $outputArray += New-Object -TypeName PSObject -Property $output
    $outputArray | Format-Table *
    Obviously in my particular case the result will be almost unreadable as a table, since there's no more no less than 42 different properties on that object, but hey, this is what you asked for! You deal with it now :D
    PS: I'm just in a good mood today. No idea why, but I am. Please don't follow my 'You deal with it now' to the letter. If you have problems or questions come back!

  • How to deal with '$' sign in the class name?

    I want to put my Java Applet game on my homepage. But the server which I set up my homepage doesn't support the file name like XXX$XXX.class, which has '$' sign in the file name. Would anyone can tell me how to deal with this problem? And how can I make the game work on my homepage? Thanks.

    Don't forget, this include both concrete inner classes as well as any anonymous inner classes you create, like
    myButton.addActionListener(new ActionListener()
      // Yada Yada Yada

  • Dealing with number range gaps with grouping?

    What i am trying to do is get a query of data that gives me a start year and end year. I can't use min and max as there could be gaps in the year.. 1999,2000,2002
    i am missing 2001 .. so i need 1999/2000 and 2002/2002
    here is a bigger example.
    Table layout
    year,color
    1998,red
    1999,red
    2001,red
    2002,red
    1997,blue
    1998,blue
    2001,blue
    2000,green
    2002,green
    2003,green
    2005,green
    Desired Output to find year ranges, accounting for gaps also.
    1998,2001,red
    1997,1998,blue
    2000,2000,blue
    2000,2000,green
    2002,20003,green
    2005,2005,green
    Anyway via SQL or PL/SQL to get this?
    The real data i'm using is a bit more complex (nothing major tho) but this is basically what i'm drilling it down to.

    Hi,
    Yes you can do that in SQL; no need for PL/SQL.
    WITH     got_grp_start  AS
         SELECT     year
         ,     color
         ,     CASE
                   WHEN  year > 1 + LAG (year) OVER ( PARTITION BY  color
                                                                ORDER BY        year
                   THEN  1
              END     AS grp_start
         FROM    table_x
    ,     got_grp          AS
         SELECT  year
         ,     color
         ,     COUNT (grp_start) OVER ( PARTITION BY  color
                                           ORDER BY      year
                               ) AS grp
         FROM     got_grp_start
    SELECT    MIN (year)     AS start_year
    ,       MAX (year)      AS end_year
    ,       color
    FROM       got_grp
    GROUP BY  color
    ,            grp
    ORDER BY  color
    ,            grp
    ;The solution above will work even if there are duplicates (2 or more rows with the same color and year).
    If there are never any duplicates, and the difference between adjacent years in the same group is always exactly 1, then there's a shorter, cuter way:
    WITH     got_grp        AS
         SELECT     year
         ,     color
         ,     year - ROW_NUMBER () OVER ( PARTITION BY  color
                                             ORDER BY         year
                               ) AS grp
         FROM     table_x
    SELECT    MIN (year)     AS start_year     -- Main query is the same as earlier
    ,       MAX (year)      AS end_year
    ,       color
    FROM       got_grp
    GROUP BY  color
    ,            grp
    ORDER BY  color
    ,            grp
    CPSteven wrote:...
    year,color
    1998,red
    1999,red
    2001,red
    2002,red
    1997,blue
    1998,blue
    2001,blue
    2000,green
    2002,green
    2003,green
    2005,green
    Desired Output to find year ranges, accounting for gaps also.
    1998,2001,red
    1997,1998,blue
    2000,2000,blue
    2000,2000,green
    2002,20003,green
    2005,2005,greenAre there some typos in the data or output?
    Edited by: Frank Kulash on Sep 4, 2009 6:06 PM

  • I need to reinstall my computer, how do I deal with Premiere pro and After effects?

    Hello,
    As my question states I need to reinstall my computer (laptop) and I'm not quite sure on how to deal with Premiere pro and After effects.
    I am thinking that I need to do some sort of backup and save my projects and footage on a sepparate drive.
    If I reinstall my computer, install my creative suit production premium, and move back all of my projects and footage, won't I have to re-link every single clip?
    I am currently workning on several different projects and having to re-link everything is something I don't even want to think about, that would take me days if not weeks.
    Another option on my mind would be to use Creative cloud. I do have the free version but I have never used it even once before and I'm not quite sure what the purpose of the cloud is and if this is a way to use it.
    I have no idea how to go about this computer reinstalation without either loosing tons of work or having to re-link every single clip used.
    I am videoediting only as a hobby so I have no experience working with other people and sharing projects or the like, wich is my understanding of what the cloud is for.
    Any and all help would be grealty appreciated, I know this is probably really easy but ever since i got my Suit I haven't reinstalled, upgraded och changed my computer so I am just clueless as to how to go about this.
    I have Creative suit production premium, I also have the free Creative cloud.
    It is only Premiere pro and After effects that I am using and am worried about.
    Thank you for any help.
    -Lisa Kajupank
    (and oh, I just notice my name - umustbejoking - I think I just wrote that cause they wouldn't let me use anything else, saying it was already taken. So nevermind that haha.)
    Message was edited by: umustbejoking

    If the computer's running Mac OS X, move the cursor to the very top of the computer's screen, click on Store, and choose Authorize this Computer.
    If the computer's running Windows, press the Alt and S keys and choose Authorize this Computer, or click here, follow the instructions, click on Store in the menu bar, and choose Authorize this Computer.
    (84620)

  • Dealing with name changes - Automatically

    Hi,
    I'm am in the process of writing a powershell script to automate our AD User account creation, modification, disabling and deletion. I am trying to figure out how to best deal with name changes with regards to exchange 2010.
    I am already able to automatically detect a name change and, rename the object in AD, the first, last and display name as well as the username and upn... so for exchange is it best to handle this through an email address policy to modify their primary smtp,
    or is there a way to do it through powershell without disabling the email address policy???
    My other question is that if the email address policy where to update the primary SMTP automatically how often with this policy execute? in other word, how long do i have to wait for the primary smtp to change after the account is renamed. Also, if i want
    to keep their old email as an alias is that doable through an email address policy or must it be done with powershell.
    Thanks

    If you want to require e-mail address policy on a recipient, the only way you can change the primary SMTP address is to change the inputs to that policy.  For example, if the policy is
    %g.%[email protected], you'll have to change the first and last names for the address to change.  If you're scripting account creation, you should consider setting -EmailAddressPolicyEnabled $False and manually managing
    the e-mail addresses through your automated process.
    Be sure not to remove the old addresses or else users will lose mail addressed to their prior addresses.
    Ed Crowley MVP "There are seldom good technological solutions to behavioral problems."

  • Export list of windows computer names with a specific relationship

    I'm trying to export only the name (netbios name) of a list of windows computers to a text file if it meets the following criteria.
    Relationship Type = "RelatedConfigItem" >  Name = "Example A"
    In other words, if the windows computer is related to another configuration item (Environment CI) with the name "Example A" it exports the computer name to a text file.  I beleive this can be done via powershell but I'm a bit new at powershell.
    Any thought on how this would be accomplished?

    Alexander,
    This is great! One issue...  When forming a relationship between a Windows Computer CI and an Environment CI it forms a one way relationship (even
    though it shows in the related items tab on either CI).
    Per Travis Wright...
    "Every relationship type has a source and target class.  For example the System.ConfigItemRelatesToConfigItem has a configuration
    that looks like this:
    This
    relationship type is a little special because it has the same class as the target and the source. So, what happens is when you create a relationship from the context of the environment form it sets the source object as the environment and the target object
    as the computer. When you create the relationship from the context of the computer form it set the source object as the computer and the environment as the target."
    All that to say, we form our relationship from the Windows Computer (source) to the Environment (target).  As such, when running the powershell
    script you provided it produces no results.
    Is there a way to reformat the script to identify Windows Computers that meet the same criteria...
    windows computer with relationship to environment A exports windows computer netbios name
    Thanks for all your help!
    James M

  • Attempt to deal with changing login account name issue

    Like many companies, we have on a regular basis people who change names due to life situations. I have tried a variety of things to deal with this in SharePoint.
    The changes start with the Active Directory admins, who create the user's new login during a night shift. I get an email about the change. When I look in the user profiles, I see that many of the fields for the user reflect the change. However, the
    actual account name attribute, which is read only to me, never changes during this period.
    So this morning, I once again web searched, found
    http://geekswithblogs.net/rgupta/archive/2011/02/16/change-accountnameloginname-for-a-sharepoint-user-spuser-again.aspx and tried the recommendation.
    I ran
    stsadm -o migrateuser -oldlogin mydomain\old -newlogin mydomain\new -ignoresidhistory
    The user does not exist or is not unique.
    PS C:\Users\sa_spfarm>
    This is the type of behavior I have gotten over time.
    For the longest time I didn't do anything since the user profile was mostly updated. Then an InfoPath programmer reported getting stale information when trying to get the user's login. After research we found that it was using the account name for the user
    rather than the login attribute (which is properly updated).
    Several times I went through adding all the people who had out of date info in their user profile.
    I recently tried to write some powershell that would at least produce a report for me of all  users in the farm whose account name differed from their logins - I was never able to get code that actually worked.
    Surely there is something simple that I am missing. I am hoping someone reads this who recognizes the problem and lets me know.
    The user profile sync is running - new user profiles appear in the system each day and as I said, in all the cases I have seen, the AD information in the profile has all been updated - except the account name (which I suspect must be an index key or something
    for the profiles).
    Thanks!
    About the only thing I have seen that works is to go into all dozen or more of our site collections and add the user's new login to an appropriate sharepoint permission group - that seems to force the account name update or at least removes the old entry
    and creates a new one (I am uncertain which it does).

    Hmm. Let me see if I can.
    Okay, so if you look at the 3 entries from the detailed user list of one of our site collections, you will see that most users are like the first and last one in this screen shot - where the login column and the user name column have the "same"
    name (one has a domain and the other doesn't... that isn't the issue to which I am referring).
    The middle person however has a user name which was the last login the user had, and has a login string with the correct domain and the correct login.
    When I go to Central Admin > manage service applications > User Profile Service Application > Manage User Profiles and I search for the old name, it is not found in either the missing or the active user profiles.
    When I search for the new name, a user profile is found. When I read through the user profile, there is no attribute which has the value of the old name.
    There are calls from users in this situation which lead us back to user list information like this.
    I have seen a user who was able to sign a document out for change in a doc library, but who could not sign it back in because "it was already out to another person" where the other person is the old name.
    Likewise, as I mentioned, if an InfoPath attempts to pull the user's information back from the sharepoint web service, there have been, at least for us, times when the old name is returned with certain methods instead of the new name.
    The interesting thing in this case is that normally I can fix these by adding the new login into a sharepoint group for the site collection. So far, that has not helped with this user.

  • Computer Name prompt with Country Code

    Using SCCM 2012 R2.. 
    Currently we have 21 global sites indicated by a two digit country code, for example United States US, United Kingdom, GB, Spain ES  etc.....
    We are a Dell shop so we want the serial number as well.
    Our end result should look like this. United States Computer
    <CountryCode>-<Serialnumber>
    US-23GHT54 for example.
    What is the best way to have a drop down or prompt for country code in computer name field when a tech starts the OSD process??

    Hi
    You can have a look at two of my blog post. The first one will show you how to enable Powershell support in your boot images:
    http://www.mimercon.dk/da/easyblog/entry/adding-powershell-support-in-configuration-manager-2012-r2-boot-images
    And the second one will guide you through all the step required to implement a Powershell GUI prompting for a Computer Name if the machine is unknown:
    http://www.mimercon.dk/da/easyblog/entry/prompt-for-computer-name-during-configmgr-2012-r2-os-deployment-1
    I know that this is not exactly what you want but you would "only" need to create your own Powershell GUI where you can select the country code and append the serial number to get your computer name generated. And then you could just follow the
    step in the second post and substitue my Prompt-Computer-Name GUI with your own.
    If you know a bit about about Windows Forms and Powershell it is fairly easy to create even though it might be easy for me to say that :)
    If you want I could create a basic GUI for you but you would have to be specific in how you would like it to look and I would need all the country codes you need in the drop-down box. You can find my e-mail at my web site.

  • I bought a new laptop with Windows 7. My computer name in Windows has changed, and now, my Ipad can't find Itunes

    I bought a new laptop with Windows 7. My computer name in Windows has changed, and now, my Ipad can't find Itunes, and Itunes can't find my Ipad. [email protected]

    Ok, if reinstalling iTunes as suggested above does not resolve the issue of iTunes recognising the iPad then try this -
    Firstly, make sure that your device is not hidden (left hand pane). If it just reads device then toggle between SHOW and HIDE.
    Secondly, try all the other ports on your computer, even a number of times.
    Thirdly, make sure your lead /connections are no faulty.
    Fourthly, if you have another computer try plugging your device into it without taking any action, give it a moment, remove it and try it back in your other computer again.
    Failing all that, see here - http://support.apple.com/kb/TS1538
    And failing all that put the device into Recovery mode. See here and note the paragraph 'If you restore from a different computer.... ' down near the bottom of the page -
    http://www.apple.com/support/ipad/assistant/itunes/
    As for making your new laptop your 'home computer' follow these instructions -
    1. Without connecting your iPad to your computer -
    A) Install iTunes / make sure the latest version of iTunes is installed.
    B) Go to the Store tab and click on "Authorise This Computer".
    C) Go to Edit, click on Preferences [iTunes and Preferences on Macs] and click on Devices. Put a check mark in the box next to "Prevent  iPods/iPhones/iPads from syncing automatically". Click OK and close iTunes.
    2.  Connect your iPad to your computer -
    A) Start iTunes (it will not start automatically because of the action at 1(C) above).
    B) Right click on your iPad under Devices in the left column. Select "Transfer purchases".
    C) When the transfer has completed, right click on your iPad again and select "Backup".
    D) When the backup has completed, left click on your iPad, click on the Apps tab, and put a check mark in the box next to "Sync Apps", and then click on "Apply" (bottom right).
    E) Unless you want to always do a manual sync (as I do), go back to Edit, Preferences [iTunes and Preferences on Macs] and uncheck the box next to "Prevent your iPod.....".
    F) Finally, on your iPad, check that everything is syncing properly. If not, go back to iTunes and check all settings.
    NB You should not lose any apps. However, any 'purchased' missing apps can be downloaded again FOC. As with updates, this must be done with the Apple ID under which they were originally 'purchased'.
    Also see here as to moving your music to your new computer -
    http://support.apple.com/kb/HT4527

  • I can't connect to other computers on my network with computer names. Any suggestions?

    i can't connect to other computers on my network with computer names. Any suggestions?

    In what way are you trying to connect? File sharing? Printer sharing? Screen sharing? Something else?
    How are your computers connected to this network? What happens when you try to connect to them?
    Best of luck.

  • How do I find the screen with my personal iPod (my name's iPod) so I can download from my purchased or free songs/pods from my computer? My iPod has opened to that for 3 years and this week I can't find it: not on purchased page or on Apple store page.

    QUESTION from an American in India:
    How do I find the screen with my personal iPod (my name's iPod) so I can download from my purchased or free songs/pods from my computer? My iPod has opened to that for 3 years and this week I can't find it: not on purchased page or on Apple store page.

    See:
    Recovering your iTunes library from your iPod or iOS device: Apple Support Communities

  • Dynamic DNS updates and issues with re-imaged / replaced machines with the same computer name

    Our AD team gets asked frequently to delete bad DNS entries because a computer was replaced or VDI was re-created, and when it was joined to the domain it had the same computer name but different SID, so the DNS entry for that computer can no longer be updated
    to a new IP address because the new computer doesn't have rights to update that object in DNS.
    I recently saw a resolution to this was to set the security for DNS to allow updates from "Domain Computers" as described in the KB below.
    http://kb.vmware.com/selfservice/microsites/search.do?language=en_US&cmd=displayKC&externalId=2005210
    Has anyone done this?  Any negative implications from this?
    Thanks

    Granting all domain computers write access to all records in the dns zone does solve the problem. On the negative side, DNS security is reduced significantly. For example, any user with admin rights locally on his/her computer will be able to sabotage
    services in your domain by deleting or changing host records of domain controllers, servers or other client computers. 
    A more secure solution in this case will be configuring DHCP servers to update DNS on behalf of the client and granting DHCP servers appropriate access to DNS zone. Take a look at
    Configuring Secure Dynamic Update for more info.
    Gleb.

  • Script for generate randomize administrator password which make log file to recorded new administrator password with associated computer name on it

    Hi
    I Need VDS script in order to change domain client local administrator password in my domain ,and put this script in startup script via group policy, but for security purpose  I want to randomize local administrator password and log new password
    set for each computer on a text file, I want to over write the old password of eachcomputer in log file with new one in order to have the update log file ,my support team some times need administrator password for troubleshooting.
    I need a script for generate randomize administrator password  which make log file to recorded new administrator password with associated computer name on it and each time new administrator password set it over write the old record on
    the log file and update the content of log file automatically.
    Regards

    Hi
    I need a script for generate randomize administrator password  which record new password on a  log file with associated computer name  and each time new administrator password set for a computer it  over write the old record
    on the log file and update the content of log file automatically.
    Regards

  • Changing the Computer name with ARD

    Hello, I am new to mac but I am now in charge of running a mac network or machines for an art department. I see that with ARD you cna change the computer name. If you change the computer name does it just change anything on the client machine? I just want to change the name in my All computers name so its easier to identify each users machine.

    There are four User-fields that you can enter information into with ARD. What I've done in the past is put the primary user of a computer into one of those fields. That way the user doesn't appear in the machine name, but I can still easily access this information.
    Note that if these computers are also in a Workgroup Manager group, that WGM will just change the name back on you. You would need to rename the computer through Workgroup Manager for this name change to take affect.

Maybe you are looking for

  • Sync just podcasts across two computers

    I have a new netbook. My desktop has iTunes. I have a lot of podcasts on there and I listen to them often through my iPod and sometimes through the desktop. All is well with syncing, I just delete listened to podcasts here and there on the pc and it

  • Downloaded programs appear with a slash through them ? ?

    Hello, I recently bought a MacBook Pro. I downloaded a free writing software from the internet (Celtx) to write screenplays. After the installation, I dragged it to the Applications folder as requested by the program. The program runs fine but in the

  • ISE Time Profiles

    I have successfully setup my guest authentication through ISE but when I change the time profile from Default Eight Hours to Default Start End the user cannot login.  If I change the profile to Eight Hours, the access is granted.  Has anyone run into

  • "sqlplus: free(): invalid pointer:" when trying to connect to SSL listener

    Hi, I'm trying to get an SSL connection configured with my Oracle 11.2.0.1 database and I am getting the following error after entering the password (and when I try to just tnsping the connection): NOTE: I cut out a big chunk of the trace dump. If yo

  • HT4236 contacts, photos lost when new iphone syncing with Macpro

    Synced my new iphone with itunes, lost all my contacts and photos, etc. iphone was restored to include all my stuff from my previous iphone, how do i fix this to get back all my new contacts and photos, etc