I'm using PowerShell to call C# code to turn list alerts on or off on a specific list. When I try to use [AlertsOnOff1.onOff]::Main("off")
to call the Main method and pass the arugment of "off"the script runs like everything went fine with zero errors, but when I create an item on the list I still get Alerts. How can I get the C# code to recognize the argument passed by PowerShell?
Add-PSSnapin Microsoft.SharePoint.PowerShell
$path = "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\ISAPI"
$Assem = @(
"$path\Microsoft.SharePoint.dll",
"System.Core"
)
$Source = @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.IO;
namespace AlertsOnOff1
{
public class onOff
{
public static void Main(string[] args)
{
args = new string[1];
string site = "http://intranet.contoso.com/";
string web = string.Empty;
string list = "ListA";
SPSite tmpSite=null;
try
{
tmpSite = new SPSite(site);
SPWeb tmpWeb = tmpSite.OpenWeb(web);
SPList tmpList = tmpWeb.Lists[list];
foreach (SPAlert tmpAlert in tmpWeb.Alerts)
{
if (args[0] == "on") //Turn it ON
{
if ((tmpAlert.List.Title == tmpList.Title) & (tmpAlert.Status == SPAlertStatus.Off))
{
tmpAlert.Status = SPAlertStatus.On;
tmpAlert.Update();
}
}
if (args[0] == "off") //Turn it OFF
{
if ((tmpAlert.List.Title == tmpList.Title) & (tmpAlert.Status == SPAlertStatus.On))
{
tmpAlert.Status = SPAlertStatus.Off;
tmpAlert.Update();
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
System.Diagnostics.EventLog.WriteEntry("Disable/Enable Alerts", ex.Message);
Console.ReadLine();
}
finally
{
//Dispose of the Root Site Object
tmpSite.Dispose();
}
}
}
}
"@
Add-Type -TypeDefinition $Source -ReferencedAssemblies $Assem
Write-Host "Turning alerts off"
[AlertsOnOff1.onOff]::Main("off")
Write-Host "Alerts turned off"
#powershell code
Update:
Originally when I didn't have args = new string[1];
I would get an error when i passed an argument through the C# code. I have now removed that line of code and passing the argument works.