0

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;
         }
     } 
    }

2 Answers 2

1

just to understand:

your asking:

Enter NWAdmin Command to perform request action:

i then type ali and it would loop through each subsite within the given site (i have 5):

so the result should be:

ali

ali

ali

ali

ali

solution:

Add-PSSnapin Microsoft.Sharepoint.Powershell

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

$spWebApp = Get-SPWebApplication http://mywebapplication:23125/

foreach ($SPSite in $spWebApp.Sites)
{
    foreach($SPWeb in $SPSite.AllWebs)
    {
        $NWAdminCommand;
    }
}

above needs to be within a file witht the extention of .ps1 , run that file within powershell! code has been tested on my server, if your looking for somthing else than please do refine your question :)

if you want to ask that question for each site looped than its in the wrong location... i dont see why you want to print the same reply for each site looped and print the same result to screen:

solution:

Add-PSSnapin Microsoft.Sharepoint.Powershell

$spWebApp = Get-SPWebApplication http://mywebapplication:23125/

foreach ($SPSite in $spWebApp.Sites)
{
    foreach($SPWeb in $SPSite.AllWebs)
    {
        $NWAdminCommand = Read-Host "Enter NWAdmin Command to perform request action"

        //do what you want with the varible $NWAdminCommand related to site $SPWeb
    }
}

above would ask the question for each site, that varible (answer) is now only related to that site and is reset every site that is iterated.

1

I'm not sure this would work. But have you tried to use Invoke-Expression

The Invoke-Expression cmdlet evaluates or runs a specified string as a command and returns the results of the expression or command. Without Invoke-Expression, a string submitted at the command line would be returned (echoed) unchanged.

http://technet.microsoft.com/en-us/library/hh849893.aspx

$cmd = '& 7z.exe a -tzip "c:\temp\with space\test2.zip" "C:\TEMP\with space\changelog"'

Invoke-Expression $cmd

https://stackoverflow.com/questions/3592851/executing-a-command-stored-in-a-variable-from-powershell

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.