Subexpression printing out same strings? Powershell

最后都变了- 提交于 2021-01-05 06:13:20

问题


I have this code which deletes User Profiles off a remote machine. The removal of profiles work just fine but, the Aesthetic of doing so doesn't. What do i mean?

  • I'm passing the user display names to an index and making a selection out of it, and that works fine in regards to assigning the proper names to the appropriate Index Number its associated to in C:\users.
  • The next line of code is it grabbing the selections i made, and running through them displaying the same name i did for the index, and then it goes off to delete the CIM instance.

So my question is, why is it not passing the subexpression $userinfo1 that is already made and not putting it into the next block of code, for example, the following works as in grabbing the proper Display Name and assigning it to the proper Number:

$menu = (get-childitem "\\$cn\c$\users"  | sort LastWriteTime -Descending).Name
$userinfo1 = foreach ($user in $menu) {
Start-Sleep -Milliseconds 2
  $userinfo = (net user $user /domain | Select-String "Full Name" -ErrorAction SilentlyContinue) -replace "Full Name                   ", "" 2>&1 | Out-String -Stream
  if ($userinfo.Length -lt 4) {    
    "$user - NO DISPLAY NAME in ADUC"  # output
  }
  else {
    if ($LASTEXITCODE -eq 2) {
      "$user   -   account not in ADUC"    # output
    }
    else {
    if ($LASTEXITCODE -eq 0){
      $userinfo  # output
        }
      }
    }
}
        Write-Warning "Ensure user profiles are no longer active and/or, have profiles be backed-up!"
            Write-Host "RESULTS:" -BackgroundColor Black -ForegroundColor White 
for ($i=0; $i -lt $userinfo1.Count; $i++) {
  Write-Host "$($i): $($userinfo1[$i])"
} #END LIST OF POSSIBLE NAMES 
             Write-Host ""
            Write-Host "For multiple users, seperate using a SPACE(1 2 3)" 
        $selection = Read-Host "ENTER THE NUMBER of the user(s) or Q to quit"
        $selection = $selection -split " "

but, the next block doesn't associate the display name (that was captured in $userinfo1) with the number i select and it just continues to display the first display name with the rest of the profiles its reiterating through:

foreach($Profile in $menu[$selection]){
    Write-Host "Deleting user: $(,$userinfo1[$selection]) `
                ID:$Profile "}

Hopefully this makes sense, and if anyone can point me in the right direction id greatly appreciate it!

Heres the rest of the script, please feel free to use it as it does work for deleting the actual profile off the system and not just the files.

#Deletes a profile properly off remote machine.  WARNING: DOES NOT BACK UP DATA!  Use at your own peril. Delprofile
$cn =  Read-Host -Prompt "Enter Computer Name"

$ping = Test-Connection -ComputerName $cn -Count 1 -Quiet 

    If($ping -eq $false){ Write-Host "Computer seems to be offline, please check name spelling." -ForegroundColor DarkYellow; Write-Host ""; &PFL-Delete } else {

$menu = (get-childitem "\\$cn\c$\users"  | sort LastWriteTime -Descending).Name

$userinfo1 = foreach ($user in $menu) {
Start-Sleep -Milliseconds 2
  $userinfo = (net user $user /domain | Select-String "Full Name" -ErrorAction SilentlyContinue) -replace "Full Name                   ", "" 2>&1 | Out-String -Stream
  if ($userinfo.Length -lt 4) {    
    "$user - NO DISPLAY NAME in ADUC"  # output
  }
  else {
    if ($LASTEXITCODE -eq 2) {
      "$user   -   account not in ADUC"    # output
    }
    else {
    if ($LASTEXITCODE -eq 0){
      $userinfo  # output
        }
      }
    }
}


        Write-Warning "Ensure user profiles are no longer active and/or, have profiles be backed-up!"

            Write-Host "RESULTS:" -BackgroundColor Black -ForegroundColor White 

for ($i=0; $i -lt $userinfo1.Count; $i++) {

  Write-Host "$($i): $($userinfo1[$i])"

} #END LIST OF POSSIBLE NAMES 

             Write-Host ""

            Write-Host "For multiple users, seperate using a SPACE(1 2 3)" 

        $selection = Read-Host "ENTER THE NUMBER of the user(s) or Q to quit"

        $selection = $selection -split " "

foreach($Profile in $menu[$selection]){


    Write-Host "Deleting user: $(,$userinfo1[$selection]) `

                ID:$Profile "

   $del = Get-CimInstance -ComputerName $cn -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('\')[-1] -eq $Profile }

   If($del -eq $null){Write-Warning "No CIM instance found on system, profile has been deleted but files persist. Delete manually!"} else{

   Get-CimInstance -ComputerName $cn -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('\')[-1] -eq $Profile } | Remove-CimInstance -WhatIf

    Write-Host "user profile has been deleted" -ForegroundColor Red

     Write-Host ""}

        }
    }
    #CountPs $cn

12/31/2020 - EDIT: Here is the finished result:

Function Delete-PFL{
#Deletes a profile properly off remote machine.  WARNING: DOES NOT BACK UP DATA!  Use at your own peril. Delprofile
$cn =  Read-Host -Prompt "Enter Computer Name"

$ping = Test-Connection -ComputerName $cn -Count 1 -Quiet 

    If($ping -eq $false){ Write-Host "Computer seems to be offline, please check name spelling." -ForegroundColor DarkYellow; Write-Host ""; &Delete-PFL } else {

$menu = (get-childitem "\\$cn\c$\users"  | sort LastWriteTime -Descending).Name

$userinfo1 = foreach ($user in $menu) {
Start-Sleep -Milliseconds 2
  $userinfo = (net user $user /domain | Select-String "Full Name" -ErrorAction SilentlyContinue) -replace "Full Name                   ", "" 2>&1 | Out-String -Stream
  if ($userinfo.Length -lt 4) {    
    "$user - NO DISPLAY NAME in ADUC"  # output
  }
  else {
    if ($LASTEXITCODE -eq 2) {
      "$user   -   ACCOUNT NOT in ADUC"    # output
    }
    else {
    if ($LASTEXITCODE -eq 0){
      $userinfo  # output
        }
      }
    }
}


        Write-Warning "Ensure user profiles are no longer active and/or, have profiles be backed-up!"

            Write-Host "RESULTS:" -BackgroundColor Black -ForegroundColor White 

for ($i=0; $i -lt $userinfo1.Count; $i++) {

  Write-Host "$($i): $($userinfo1[$i])"

} #END LIST OF POSSIBLE NAMES 

             Write-Host ""

            Write-Host "For multiple users, seperate using a SPACE(1 2 3)" 

        $selection = Read-Host "ENTER THE NUMBER of the user(s) or Q to quit"

        $selection = $selection -split " "


foreach($index in $selection) {
    $Profile = $menu[$index]
    Write-Host "Deleting user: $($userinfo1[$index]) `
                ID:$Profile "
  


   $del = Get-CimInstance -ComputerName $cn -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('\')[-1] -eq $Profile }

   If($del -eq $null){Write-Warning "No CIM instance found on system, profile has been deleted but files persist."    
    Write-Host "Attempting to delete files, please wait. . ." 
     
     Remove-Item -Path "\\$cn\c$\users\$Profile" -Force -WhatIf       
     Write-Host ""
     
     Start-Sleep -Seconds 2
    Write-Host "Checking if Files are still there. . ."

$TestPath = Test-Path -Path "\\$cn\c$\users\$Profile"    
   If($TestPath -eq $false){ Write-Host "Profile Files have been deleted. `
   Continuing. . . ." -ForegroundColor Green
                 }
   } else{

   Get-CimInstance -ComputerName $cn -Class Win32_UserProfile | Where-Object { $_.LocalPath.split('\')[-1] -eq $Profile } | Remove-CimInstance -WhatIf

    Write-Host "user profile has been deleted" -ForegroundColor Red

     Write-Host ""
                
            }

        }
    }
    #CountPs $cn
}

Remember to remove the -whatif parameter. Enjoy!


回答1:


$selection is an array of indices, so in your foreach loop you must refer to the single index at hand, not to $selection as a whole, to get the desired display output.

The conceptually clearest approach is probably to iterate over the indices contained in $selection:

foreach($index in $selection) {
    $Profile = $menu[$index]
    Write-Host "Deleting user: $($userinfo1[$index]) `
                EDIPI:$Profile "
    # ...
}


来源:https://stackoverflow.com/questions/65511699/subexpression-printing-out-same-strings-powershell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!