Forum Discussion

charlie4872's avatar
charlie4872
Brass Contributor
Jun 03, 2020
Solved

Using multiple variables against single command

I am working with a loop in a script and am trying to get multiple variables for use in a single command. This is a hard one to verbalize for a Google search so I figured I would try here. The script I am running is this....

 

$username = get-content c:\temp\users.txt
$newadmin = Read-Host 'Enter New Admin'
$OneDriveUrl = Get-PnPUserProfileProperty -Account $username | select-object PersonalUrl
foreach ($user in $username){
Set-SPOUser -Site $OneDriveUrl.PersonalUrl -LoginName $newadmin -IsSiteCollectionAdmin $True -ErrorAction SilentlyContinue}

What I am trying to accomplish is to take the info gathered in the $username, $newadmin and $OneDriveUrl variables and loop them against the Set-SPOUser command in the last line of the script. The script works fine without the foreach loop for doing user by user individually, but I have a large list of users who I want to work with. Would love some help on how I can gather all the info from the variables and run them against the final Set-SPOUser command at the end. I appreciate the help and thanks in advance!!

  • The script looks OK, although you need to move the $OneDriveUrl part inside the loop (otherwise it will always return the same value).  I would suggest generating a list of individual ODFB URLs first, then combining it with the username in a CSV file. That way you can simply reference the different values via say $_.UserName, $_.OneDriveUrl and so on.

4 Replies

  • The script looks OK, although you need to move the $OneDriveUrl part inside the loop (otherwise it will always return the same value).  I would suggest generating a list of individual ODFB URLs first, then combining it with the username in a CSV file. That way you can simply reference the different values via say $_.UserName, $_.OneDriveUrl and so on.

    • charlie4872's avatar
      charlie4872
      Brass Contributor

      Thanks for the response VasilMichev I tried moving the $OneDriveUrl portion of the script inside the loop and no dice. Although I may have it wrong. I have to admit I am not a Powershell wiz by any means. I have change the script like below...

       

      $username = get-content c:\temp\users.txt
      $newadmin = Read-Host 'Enter New Admin'
      foreach ($user in $username){
      $OneDriveUrl = Get-PnPUserProfileProperty -Account $username | select-object PersonalUrl
      Set-SPOUser -Site $OneDriveUrl.PersonalUrl -LoginName $newadmin -IsSiteCollectionAdmin $True -ErrorAction SilentlyContinue}
      • VasilMichev's avatar
        VasilMichev
        MVP

        Inside the loop, you should be using $user instead of $username.

Resources