powershell 此示例在powershell中运行C#代码。我需要这个,当有一部分代码要测试但它只能在p中测试

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了powershell 此示例在powershell中运行C#代码。我需要这个,当有一部分代码要测试但它只能在p中测试相关的知识,希望对你有一定的参考价值。

$Assem = ( 
    "Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c",
    #"Microsoft.SharePoint.Administration, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c",
    "Microsoft.SharePoint.Publishing, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" 
    ) 


$Source = @"
using Microsoft.SharePoint.Publishing.Administration;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System; 

namespace MikeG2.Test 
{ 

public static class UpdateToday 
    {
        private static string _curVersion = "1.0.4";
        public static void Get() 
        { 
      // for each site collection .. update the "today" function
        string _logMessage = "";
        SPDiagnosticsService diagnosticsService = SPDiagnosticsService.Local;
        SPDiagnosticsCategory cat = diagnosticsService.Areas["SharePoint Foundation"].Categories["Unknown"];

        _logMessage = "Dynamic Today Timer Service Started";
        SPDiagnosticsService.Local.WriteTrace(1, cat, TraceSeverity.Medium, _logMessage, cat.Name, cat.Area.Name);

      //   false = won't use SPContext.  true does
      //   false starts at the Farm level and searches down for the first WSS root Site Collection
      SPFarm farm = SPFarm.Local;
      SPListItemCollection listItems = null;
      foreach (SPService service in farm.Services) {
        SPWebService webService = service as SPWebService;
        // webService.TypeName is found Central Admin Services on Server
        if (webService != null && webService.TypeName == "Microsoft SharePoint Foundation Web Application")
        {
          foreach (SPWebApplication app in webService.WebApplications) {
            //Console.WriteLine ("DT Application: {0}" + " - {1}", app.DisplayName, app.Name);
            _logMessage = "DT Application: " + app.DisplayName + " - " + app.Name + ", Version: " + _curVersion;
            SPDiagnosticsService.Local.WriteTrace(1, cat, TraceSeverity.Medium, _logMessage);

            foreach (SPContentDatabase db in app.ContentDatabases) {
              // db.Name
              //Console.WriteLine ("DB Name: {0}", db.Name);
              _logMessage = "DT DB Name: " + db.Name;
              SPDiagnosticsService.Local.WriteTrace(1, cat, TraceSeverity.Medium, _logMessage);
              int count = 0;
              foreach (SPSite siteCollection in db.Sites) {
                //Console.WriteLine ("Site Collection URL: {0}", siteCollection.ServerRelativeUrl);
                _logMessage = "DT Site Collection URL: " + siteCollection.ServerRelativeUrl.ToString();
                SPDiagnosticsService.Local.WriteTrace(1, cat, TraceSeverity.Medium, _logMessage);
                count++;
                foreach (SPWeb site in siteCollection.AllWebs) {
                  foreach (SPList list in site.Lists) {
                    try {
                      foreach (SPField field in list.Fields) {
                        if (field.FieldReferences != null) {
                          foreach (String fieldRef in field.FieldReferences) {
                            if (fieldRef.ToUpper () == "TODAY") {
                              site.AllowUnsafeUpdates = true;

                              // turn off events .. we're not changing anything ...
                              HandleEventFiring eventFiring = new HandleEventFiring ();
                              eventFiring.CustomDisableEventFiring ();

                              // everytime we call list.Items .. it querys the database
                              // so copy these item into a SPListItemCollection and use that
                              listItems = list.Items;

                              try {
                                foreach (SPListItem item in listItems) {
                                  item.SystemUpdate (false); // false tells it to NOT update the version level
                                }
                                _logMessage = "DT Site: " + site.Title + ",  List: " + list.Title + ", Items Updated: " + list.ItemCount.ToString ();
                              }
                              catch (Exception ex) {
                                _logMessage = "ERROR - DT Site: " + site.Title + ", List: " + list.Title + ", Exception: " + ex.Message;
                              }
                              finally {
                                site.AllowUnsafeUpdates = false;
                                // turn events back on
                                eventFiring.CustomEnableEventFiring ();
                              }

                              SPDiagnosticsService.Local.WriteTrace(1, cat, TraceSeverity.Medium, _logMessage, cat.Name, cat.Area.Name);
                            } // if (fieldRef
                          } // foreach (String fieldRef
                        } // if !field.FieldReferences == null
                      } // foreach (SPField field
                    }
                    catch (Exception ex) {
                      _logMessage = "Site: " + site.Title + ", List: " + list.Title + ", Exception: " + ex.Message;
                      SPDiagnosticsService.Local.WriteTrace(1, cat, TraceSeverity.Medium, _logMessage, cat.Name, cat.Area.Name);
                    }
                  } // foreach (SPList list
                  site.Dispose ();
                } // foreach (SPWeb site
                siteCollection.Dispose ();
              } // foreach (SPSite siteCollection
            } // foreach (SPContentDatabase db
          } // foreach (SPWebApplication app
        } // if (webService != null
      } //foreach (SPService service
      SPDiagnosticsService.Local.WriteTrace(1, cat, TraceSeverity.Medium, _logMessage, cat.Name, cat.Area.Name);
      }//end the function
    }//close class
    
      public class HandleEventFiring : SPItemEventReceiver
      {
        /// <summary>
        /// 
        /// </summary>
        public HandleEventFiring ()
        {
        }
        /// <summary>
        /// 
        /// </summary>
        public void CustomDisableEventFiring ()
        {
          //this.DisableEventFiring ();
          this.EventFiringEnabled = false;
        }
        /// <summary>
        /// 
        /// </summary>
        public void CustomEnableEventFiring ()
        {
          //this.EnableEventFiring ();
          this.EventFiringEnabled = true;
        }
      }

}//close namespace
"@ 
Add-Type -ReferencedAssemblies $Assem -TypeDefinition $Source -Language CSharp  

[MikeG2.Test.UpdateToday]::Get()
$Assem = ( 
    "Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c",
    #"Microsoft.SharePoint.Administration, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c",
    "Microsoft.SharePoint.Publishing, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" 
    ) 


$Source = @"
using Microsoft.SharePoint.Publishing.Administration;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System; 

namespace MikeG2.Test 
{ 

public static class UpdateToday 
    {
        private static string _curVersion = "1.0.4";
        public static void Get() 
        { 
      // for each site collection .. update the "today" function
        string _logMessage = "";
        SPDiagnosticsService diagnosticsService = SPDiagnosticsService.Local;
        SPDiagnosticsCategory cat = diagnosticsService.Areas["SharePoint Foundation"].Categories["Unknown"];

        _logMessage = "Dynamic Today Timer Service Started";
        SPDiagnosticsService.Local.WriteTrace(2, cat, TraceSeverity.Medium, _logMessage, cat.Name, cat.Area.Name);

      //   false = won't use SPContext.  true does
      //   false starts at the Farm level and searches down for the first WSS root Site Collection
      SPFarm farm = SPFarm.Local;
      SPListItemCollection listItems = null;
      foreach (SPService service in farm.Services) {
        SPWebService webService = service as SPWebService;
        // webService.TypeName is found Central Admin Services on Server
        if (webService != null && webService.TypeName == "Microsoft SharePoint Foundation Web Application")
        {
          foreach (SPWebApplication app in webService.WebApplications) {
            //Console.WriteLine ("DT Application: {0}" + " - {1}", app.DisplayName, app.Name);
            _logMessage = "DT Application: " + app.DisplayName + " - " + app.Name + ", Version: " + _curVersion;
            SPDiagnosticsService.Local.WriteTrace(2, cat, TraceSeverity.Medium, _logMessage);

            foreach (SPContentDatabase db in app.ContentDatabases) {
              // db.Name
              //Console.WriteLine ("DB Name: {0}", db.Name);
              _logMessage = "DT DB Name: " + db.Name;
              SPDiagnosticsService.Local.WriteTrace(2, cat, TraceSeverity.Medium, _logMessage);
              int count = 0;
              foreach (SPSite siteCollection in db.Sites) {
                //Console.WriteLine ("Site Collection URL: {0}", siteCollection.ServerRelativeUrl);
                _logMessage = "DT Site Collection URL: " + siteCollection.ServerRelativeUrl.ToString();
                SPDiagnosticsService.Local.WriteTrace(2, cat, TraceSeverity.Medium, _logMessage);
                count++;
                foreach (SPWeb site in siteCollection.AllWebs) {
                  foreach (SPList list in site.Lists) {
                    try {
			_logMessage = "DT Site: " + site.Title + ",  List: " + list.Title;
			SPDiagnosticsService.Local.WriteTrace(2, cat, TraceSeverity.Medium, _logMessage);
                      foreach (SPField field in list.Fields) {
                        if (field.FieldReferences != null) {
                          foreach (String fieldRef in field.FieldReferences) {
///Everything with three "///" has been commented out to prevent executing against the list items
                            if (fieldRef.ToUpper () == "TODAY") {
                              ///site.AllowUnsafeUpdates = true;

                              // turn off events .. we're not changing anything ...
                              HandleEventFiring eventFiring = new HandleEventFiring ();
                              ///eventFiring.CustomDisableEventFiring ();

                              // everytime we call list.Items .. it querys the database
                              // so copy these item into a SPListItemCollection and use that
                              listItems = list.Items;

                              try {
                                foreach (SPListItem item in listItems) {
                                  ///item.SystemUpdate (false); // false tells it to NOT update the version level
				  string xx = "";
				  xx += "f";
                                }
                                _logMessage = "DT Site: " + site.Title + ",  List: " + list.Title + ", Items Updated: " + list.ItemCount.ToString ();
                              }
                              catch (Exception ex) {
                                _logMessage = "ERROR - DT Site: " + site.Title + ", List: " + list.Title + ", Exception: " + ex.Message;
                              }
                              finally {
                                ///site.AllowUnsafeUpdates = false;
                                // turn events back on
                                ///eventFiring.CustomEnableEventFiring ();
				string yy = "";
				yy += "f";
                              }

                              SPDiagnosticsService.Local.WriteTrace(2, cat, TraceSeverity.Medium, _logMessage, cat.Name, cat.Area.Name);
                            } // if (fieldRef
                          } // foreach (String fieldRef
                        } // if !field.FieldReferences == null
                      } // foreach (SPField field
                    }
                    catch (Exception ex) {
                      _logMessage = "Site: " + site.Title + ", List: " + list.Title + ", Exception: " + ex.Message;
                      SPDiagnosticsService.Local.WriteTrace(2, cat, TraceSeverity.Medium, _logMessage, cat.Name, cat.Area.Name);
                    }
                  } // foreach (SPList list
                  site.Dispose ();
                } // foreach (SPWeb site
                siteCollection.Dispose ();
              } // foreach (SPSite siteCollection
            } // foreach (SPContentDatabase db
          } // foreach (SPWebApplication app
        } // if (webService != null
      } //foreach (SPService service
      SPDiagnosticsService.Local.WriteTrace(2, cat, TraceSeverity.Medium, _logMessage, cat.Name, cat.Area.Name);
      }//end the function
    }//close class
    
      public class HandleEventFiring : SPItemEventReceiver
      {
        /// <summary>
        /// 
        /// </summary>
        public HandleEventFiring ()
        {
        }
        /// <summary>
        /// 
        /// </summary>
        public void CustomDisableEventFiring ()
        {
          //this.DisableEventFiring ();
          this.EventFiringEnabled = false;
        }
        /// <summary>
        /// 
        /// </summary>
        public void CustomEnableEventFiring ()
        {
          //this.EnableEventFiring ();
          this.EventFiringEnabled = true;
        }
      }

}//close namespace
"@ 
Add-Type -ReferencedAssemblies $Assem -TypeDefinition $Source -Language CSharp  

[MikeG2.Test.UpdateToday]::Get()

$path = "F:\temp\temp.log"
If (Test-Path $path){
	Remove-Item $path
}

Merge-SPLogFile -path $path -Overwrite -EventID 2 -StartTime "03/31/2017 10:04" -EndTime "03/31/2017 12:30"
Get-Content $path
notepad $path
$Assem = ( 
    "Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c",
    #"Microsoft.SharePoint.Administration, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c",
    "Microsoft.SharePoint.Publishing, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" 
    ) 


$Source = @"
using Microsoft.SharePoint.Publishing.Administration;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System; 

namespace MikeG2.Test 
{ 

public static class UpdateToday 
{
private static string _curVersion = "1.0.4";
public static void Doit()
    {
      // for each site collection .. update the "today" function
        string _logMessage = "";
        SPDiagnosticsService diagnosticsService = SPDiagnosticsService.Local;
        SPDiagnosticsCategory cat = diagnosticsService.Areas["SharePoint Foundation"].Categories["Unknown"];
        //SPDiagnosticsCategory cat = new SPDiagnosticsCategory("DynamicToday", TraceSeverity.High, EventSeverity.Warning);

        _logMessage = "Dynamic Today Timer Service Started";
        SPDiagnosticsService.Local.WriteTrace(2, cat, TraceSeverity.Medium, _logMessage, cat.Name, cat.Area.Name);

      //   false = won't use SPContext.  true does
      //   false starts at the Farm level and searches down for the first WSS root Site Collection
      SPFarm farm = SPFarm.Local;
      SPListItemCollection listItems = null;
      foreach (SPService service in farm.Services) {
        SPWebService webService = service as SPWebService;
        // webService.TypeName is found Central Admin Services on Server
        if (webService != null && webService.TypeName == "Microsoft SharePoint Foundation Web Application")
        {
		SPWebApplicationCollection apps = webService.WebApplications;
          foreach (SPWebApplication app in apps) {
            //Console.WriteLine ("DT Application: {0}" + " - {1}", app.DisplayName, app.Name);
            _logMessage = "DT Application: " + app.DisplayName + " - " + app.Name + ", Version: " + _curVersion;
            SPDiagnosticsService.Local.WriteTrace(2, cat, TraceSeverity.Medium, _logMessage);

		SPContentDatabaseCollection spc = app.ContentDatabases;
            foreach (SPContentDatabase db in spc) {
              // db.Name
              //Console.WriteLine ("DB Name: {0}", db.Name);
              _logMessage = "DT DB Name: " + db.Name;
		if(db.Name == "WSS_Content_130"){
              SPDiagnosticsService.Local.WriteTrace(2, cat, TraceSeverity.Medium, _logMessage);
              int count = 0;
              try
              {
		SPSiteCollection sc = db.Sites;
                  foreach (SPSite siteCollection in sc)
                  {
                      //Console.WriteLine ("Site Collection URL: {0}", siteCollection.ServerRelativeUrl);
                      _logMessage = "DT Site Collection URL: " + siteCollection.ServerRelativeUrl.ToString();
                      SPDiagnosticsService.Local.WriteTrace(2, cat, TraceSeverity.Medium, _logMessage);
                      count++;
                      foreach (SPWeb site in siteCollection.AllWebs)
                      {
                          _logMessage = "DT Site URL: " + site.ServerRelativeUrl.ToString();
                          SPDiagnosticsService.Local.WriteTrace(2, cat, TraceSeverity.Medium, _logMessage);
                          foreach (SPList list in site.Lists)
                          {
				_logMessage = "DT List URL: " + list.Title;
                          	SPDiagnosticsService.Local.WriteTrace(2, cat, TraceSeverity.Medium, _logMessage);
                              try
                              {
                                  foreach (SPField field in list.Fields)
                                  {
                                      if (field.FieldReferences != null)
                                      {
						_logMessage = "DT Field Ref Found: " + field.Title;
		                          	SPDiagnosticsService.Local.WriteTrace(2, cat, TraceSeverity.Medium, _logMessage);
                                          foreach (String fieldRef in field.FieldReferences)
                                          {
                                              if (fieldRef.ToUpper() == "TODAY")
                                              {
                                                  site.AllowUnsafeUpdates = true;

                                                  // turn off events .. we're not changing anything ...
                                                  HandleEventFiring eventFiring = new HandleEventFiring();
                                                  eventFiring.CustomDisableEventFiring();

                                                  // everytime we call list.Items .. it querys the database
                                                  // so copy these item into a SPListItemCollection and use that
                                                  listItems = list.Items;

                                                  try
                                                  {
                                                      foreach (SPListItem item in listItems)
                                                      {
                                                          item.SystemUpdate(false); // false tells it to NOT update the version level
                                                      }
                                                      _logMessage = "DT Site: " + site.Title + ",  List: " + list.Title + ", Items Updated: " + list.ItemCount.ToString();
                                                  }
                                                  catch (Exception ex)
                                                  {
                                                      _logMessage = "ERROR - DT Site: " + site.Title + ", List: " + list.Title + ", Exception: " + ex.Message;
                                                  }
                                                  finally
                                                  {
                                                      site.AllowUnsafeUpdates = false;
                                                      // turn events back on
                                                      eventFiring.CustomEnableEventFiring();
                                                  }

                                                  SPDiagnosticsService.Local.WriteTrace(2, cat, TraceSeverity.Medium, _logMessage, cat.Name, cat.Area.Name);
                                              } // if (fieldRef
                                          } // foreach (String fieldRef
                                      } // if !field.FieldReferences == null
                                  } // foreach (SPField field
                              }
                              catch (Exception ex)
                              {
                                  _logMessage = "Site: " + site.Title + ", List: " + list.Title + ", Exception: " + ex.Message;
                                  SPDiagnosticsService.Local.WriteTrace(2, cat, TraceSeverity.Medium, _logMessage, cat.Name, cat.Area.Name);
                              }
                          } // foreach (SPList list
                          site.Dispose();
                      } // foreach (SPWeb site
                      siteCollection.Dispose();
                  } // foreach (SPSite siteCollection
              }
              catch (Exception ex)
              {
                  _logMessage = "Error encountered at the site collection level, Exception: " + ex.Message;
                  SPDiagnosticsService.Local.WriteTrace(2, cat, TraceSeverity.Medium, _logMessage, cat.Name, cat.Area.Name);
              }
		}//end if
            } // foreach (SPContentDatabase db
          } // foreach (SPWebApplication app
        } // if (webService != null
      } //foreach (SPService service
      SPDiagnosticsService.Local.WriteTrace(2, cat, TraceSeverity.Medium, _logMessage, cat.Name, cat.Area.Name);
    }
    }//end the class
    
    public class HandleEventFiring : SPItemEventReceiver
  {
    /// <summary>
    /// 
    /// </summary>
    public HandleEventFiring ()
    {
    }
    /// <summary>
    /// 
    /// </summary>
    public void CustomDisableEventFiring ()
    {
      //this.DisableEventFiring ();
      this.EventFiringEnabled = false;
    }
    /// <summary>
    /// 
    /// </summary>
    public void CustomEnableEventFiring ()
    {
      //this.EnableEventFiring ();
      this.EventFiringEnabled = true;
    }
  }
  
}//close namespace
"@ 

Add-Type -ReferencedAssemblies $Assem -TypeDefinition $Source -Language CSharp  

[MikeG2.Test.UpdateToday]::Doit()

以上是关于powershell 此示例在powershell中运行C#代码。我需要这个,当有一部分代码要测试但它只能在p中测试的主要内容,如果未能解决你的问题,请参考以下文章

为什么Powershell类属性在其方法中需要此属性?

如何在 Powershell 中手动增加 $err 计数?

PowerShell命令

powershell 我的示例Powershell配置文件脚本

powershell PowerShell自定义对象示例

powershell AIM CCP PowerShell示例