2

I have written a power shell command to achieve a specific function and I'm new to power shell. That should perform the action and I'm pretty sure I have entered exact working command. But when I try to execute the command inside for each loop, it prints the command rather than executing. NWAdminCommand is my command and it gets values from user input.

$NWAdminCommand = Read-Host "Enter NWAdmin Command to perform request action"

foreach ($SPSite in $spWebApp.Sites)
    {

      foreach($SPWeb in $SPSite.AllWebs)
         {
    $NWAdminCommand;
         }
     } 
    }
Sivakumar Piratheeban
  • 493
  • 4
  • 11
  • 39

1 Answers1

2

This line $NWAdminCommand is equivalent to Write-Host $NWAdminCommand. In order to execute a command you can prefix it with & or use iex.

 & $NWAdminCommand
 iex $NWAdminCommand

You can check this SO question or this Microsoft Technet web page that explains all the different ways of executing commands.

This is the correct code (assumming that $spWebApp.Sites and $SPSite.AllWebs are not empty collections)

$NWAdminCommand = Read-Host "Enter NWAdmin Command to perform request action"
foreach ($SPSite in $spWebApp.Sites)
{
      foreach($SPWeb in $SPSite.AllWebs)
      {
            & $NWAdminCommand
            #iex $NWAdminCommand
      }
} 
Community
  • 1
  • 1
Oscar Foley
  • 6,817
  • 8
  • 57
  • 90