Question

I have written a powershell script with couple of methods. I want to start powershell script with some specific method,for example the script should start with method Get-SitesWithNewsPageCT() How I specify in Script? Secondly, I have declared some global variables at start of script to use in methods. How methods will know about these variables for example how the function Get-SitesWithNewsPageCT() will know the value of variable $Global:site

Please correct method declaration if something wrong

$WepApp = "http://somesite.mysite.int/"
$Global:site = Get-SPSite $WepApp

Function Get-SitesWithNewsPageCT()
{
   $Global:site | Get-SPWeb -Limit all | ForEach-Object { 
   $PagesLibrary = $_.Lists[$Global:lookForList]

    Remove-NewsPageCT $PagesLibrary $_
    }     
}

Function Remove-NewsPageCT($PagesLibrary,$web)
{
  # do some stuff here
  Add-NewsPageCT $PagesLibrary $count
}

Function Add-NewsPageCT($PagesLibrary,$count)
{
  # do some stuff here
}
Was it helpful?

Solution

The execution of the script is from top to bottom. You have declare both of the variables at top, so they will get assigned with values.

After that you have defined few methods which makes use of it. During script execution these method definitions will not be executed unless they are called. Which I think is part of your question.

So to start or run the script. Refer below code update.

$WepApp = "http://somesite.mysite.int/"
$Global:site = Get-SPSite $WepApp

Function Get-SitesWithNewsPageCT()
{
$Global:site | Get-SPWeb -Limit all | ForEach-Object { 
$PagesLibrary = $_.Lists[$Global:lookForList]

    Remove-NewsPageCT $PagesLibrary $_
    }     
}

Function Remove-NewsPageCT($PagesLibrary,$web)
{
# do some stuff here
Add-NewsPageCT $PagesLibrary $count
}

Function Add-NewsPageCT($PagesLibrary,$count)
{
# do some stuff here
}


# Call function
#
Get-SitesWithNewsPageCT

By the time function Get-SitesWithNewsPageCT is getting executed the global varidable $Global:site will have value in it.

Update:

This blog How To Make Use Of Functions in PowerShell has good examples to run functions read the 3rd option, that's what I have explained

OTHER TIPS

I don't know how your question is related to SharePoint, but I usually write like this (good old main(argc,argv) C-style single entry point):

$main = {
    <call to Get-SitesWithNewsPageCT>
}

function Get-SitesWithNewsPageCT() {
    <some code>
}

& $main

Mr. Wilson is the best source of Powershell how to's

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top