Add project files.
parent
170ef7ef1e
commit
e737b68fdd
|
@ -0,0 +1,25 @@
|
|||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 16
|
||||
VisualStudioVersion = 16.0.29609.76
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "MyLLDP", "MyLLDP\MyLLDP.csproj", "{86C1533D-D009-49DB-88E1-DDA02191A88F}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{86C1533D-D009-49DB-88E1-DDA02191A88F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{86C1533D-D009-49DB-88E1-DDA02191A88F}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{86C1533D-D009-49DB-88E1-DDA02191A88F}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{86C1533D-D009-49DB-88E1-DDA02191A88F}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
GlobalSection(ExtensibilityGlobals) = postSolution
|
||||
SolutionGuid = {B9101403-CBA6-4867-B132-B0C99FB5ABB4}
|
||||
EndGlobalSection
|
||||
EndGlobal
|
|
@ -0,0 +1,14 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<configuration>
|
||||
<startup>
|
||||
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
|
||||
</startup>
|
||||
<runtime>
|
||||
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
|
||||
<dependentAssembly>
|
||||
<assemblyIdentity name="System.Numerics.Vectors" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
|
||||
<bindingRedirect oldVersion="0.0.0.0-4.1.4.0" newVersion="4.1.4.0" />
|
||||
</dependentAssembly>
|
||||
</assemblyBinding>
|
||||
</runtime>
|
||||
</configuration>
|
|
@ -0,0 +1,9 @@
|
|||
<Application x:Class="MyLLDP.App"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:local="clr-namespace:MyLLDP"
|
||||
StartupUri="MainWindow.xaml">
|
||||
<Application.Resources>
|
||||
|
||||
</Application.Resources>
|
||||
</Application>
|
|
@ -0,0 +1,17 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Configuration;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
|
||||
namespace MyLLDP
|
||||
{
|
||||
/// <summary>
|
||||
/// Interaction logic for App.xaml
|
||||
/// </summary>
|
||||
public partial class App : Application
|
||||
{
|
||||
}
|
||||
}
|
|
@ -0,0 +1,98 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Drawing;
|
||||
using System.Diagnostics;
|
||||
|
||||
namespace SMM.Helper
|
||||
{
|
||||
public static class Extensions
|
||||
{
|
||||
private readonly static object _lock = new object();
|
||||
|
||||
public static T CloneObject<T>(T original)
|
||||
{
|
||||
try
|
||||
{
|
||||
Monitor.Enter(_lock);
|
||||
T copy = Activator.CreateInstance<T>();
|
||||
PropertyInfo[] piList = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
|
||||
foreach (PropertyInfo pi in piList)
|
||||
{
|
||||
if (pi.GetValue(copy, null) != pi.GetValue(original, null))
|
||||
{
|
||||
try
|
||||
{
|
||||
pi.SetValue(copy, pi.GetValue(original, null), null);
|
||||
}
|
||||
catch (Exception e) when (e.Message == "Property set method not found.")
|
||||
{
|
||||
// I don't care about not being able to set private properties
|
||||
}
|
||||
}
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Monitor.Exit(_lock);
|
||||
}
|
||||
}
|
||||
|
||||
public static T CloneObject<T>(T original, List<string> propertyExcludeList)
|
||||
{
|
||||
try
|
||||
{
|
||||
Monitor.Enter(_lock);
|
||||
T copy = Activator.CreateInstance<T>();
|
||||
PropertyInfo[] piList = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
|
||||
foreach (PropertyInfo pi in piList)
|
||||
{
|
||||
if (!propertyExcludeList.Contains(pi.Name))
|
||||
{
|
||||
if (pi.GetValue(copy, null) != pi.GetValue(original, null))
|
||||
{
|
||||
pi.SetValue(copy, pi.GetValue(original, null), null);
|
||||
}
|
||||
}
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
finally
|
||||
{
|
||||
Monitor.Exit(_lock);
|
||||
}
|
||||
}
|
||||
|
||||
public static IEnumerable<TSource> FromHierarchy<TSource>(
|
||||
this TSource source,
|
||||
Func<TSource, TSource> nextItem,
|
||||
Func<TSource, bool> canContinue)
|
||||
{
|
||||
for (var current = source; canContinue(current); current = nextItem(current))
|
||||
{
|
||||
yield return current;
|
||||
}
|
||||
}
|
||||
|
||||
public static IEnumerable<TSource> FromHierarchy<TSource>(
|
||||
this TSource source,
|
||||
Func<TSource, TSource> nextItem)
|
||||
where TSource : class
|
||||
{
|
||||
return FromHierarchy(source, nextItem, s => s != null);
|
||||
}
|
||||
|
||||
public static string GetAllMessages(this Exception exception)
|
||||
{
|
||||
var messages = exception.FromHierarchy(ex => ex.InnerException)
|
||||
.Select(ex => ex.Message);
|
||||
return String.Join(Environment.NewLine, messages);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,32 @@
|
|||
<Window x:Class="MyLLDP.MainWindow"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
|
||||
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
|
||||
xmlns:local="clr-namespace:MyLLDP"
|
||||
mc:Ignorable="d"
|
||||
Title="MainWindow" Height="450" Width="800">
|
||||
<Grid>
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition/>
|
||||
<RowDefinition Height="64"/>
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<TextBlock x:Name="LldpOut"
|
||||
Grid.Row="0"
|
||||
Text="{Binding Path=Results, Mode=OneWay}"/>
|
||||
|
||||
|
||||
<UniformGrid Grid.Row="1"
|
||||
Rows="1"
|
||||
Columns="4"
|
||||
VerticalAlignment="Stretch">
|
||||
<Canvas/>
|
||||
<Button x:Name="BtnScan"
|
||||
VerticalAlignment="Stretch"
|
||||
IsEnabled="{Binding Enabled}"
|
||||
Command="{Binding StartCapture}">Scan</Button>
|
||||
<Button>Cancel</Button>
|
||||
</UniformGrid>
|
||||
</Grid>
|
||||
</Window>
|
|
@ -0,0 +1,88 @@
|
|||
using MvvmHelpers;
|
||||
using SMM.Automation;
|
||||
using SMM.Command;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Management.Automation;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
using System.Windows.Data;
|
||||
using System.Windows.Documents;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
using System.Windows.Media.Imaging;
|
||||
using System.Windows.Navigation;
|
||||
using System.Windows.Shapes;
|
||||
|
||||
namespace MyLLDP
|
||||
{
|
||||
/// <summary>
|
||||
/// Interaction logic for MainWindow.xaml
|
||||
/// </summary>
|
||||
public partial class MainWindow : Window
|
||||
{
|
||||
public MainWindow()
|
||||
{
|
||||
InitializeComponent();
|
||||
|
||||
DataContext = new MainWindowViewModel();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public class MainWindowViewModel : BaseViewModel
|
||||
{
|
||||
|
||||
public MainWindowViewModel()
|
||||
{
|
||||
ScriptRunner = new SimpleScriptRunner(Properties.Resources.script1);
|
||||
ScriptRunner.ScriptFragments.Add(ScriptBlock.Create(Properties.Resources.script2));
|
||||
ScriptRunner.ScriptFragments.Add(ScriptBlock.Create(Properties.Resources.script3));
|
||||
|
||||
ScriptRunner.PropertyChanged += ScriptRunner_PropertyChanged;
|
||||
}
|
||||
|
||||
|
||||
private void ScriptRunner_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
|
||||
{
|
||||
if (e.PropertyName == "Results")
|
||||
{
|
||||
OnPropertyChanged(nameof(Results));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private string _results;
|
||||
public string Results { get {
|
||||
_results = String.Join(Environment.NewLine, ScriptRunner.Results.Select(x => x.ToString()));
|
||||
return _results;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private bool _enabled;
|
||||
public bool Enabled { get => _enabled; set => SetProperty(ref _enabled, value); }
|
||||
|
||||
|
||||
private SimpleScriptRunner _scriptRunner;
|
||||
public SimpleScriptRunner ScriptRunner { get => _scriptRunner; set => SetProperty(ref _scriptRunner, value); }
|
||||
|
||||
|
||||
private RelayCommand _startCap;
|
||||
public ICommand StartCapture {
|
||||
get {
|
||||
if (_startCap == null)
|
||||
{
|
||||
Enabled = false;
|
||||
_startCap = new RelayCommand(
|
||||
() => ScriptRunner?.Run() ) ;
|
||||
Enabled = true;
|
||||
}
|
||||
return _startCap;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,115 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectGuid>{86C1533D-D009-49DB-88E1-DDA02191A88F}</ProjectGuid>
|
||||
<OutputType>WinExe</OutputType>
|
||||
<RootNamespace>MyLLDP</RootNamespace>
|
||||
<AssemblyName>MyLLDP</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
|
||||
<Deterministic>true</Deterministic>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="MvvmHelpers, Version=1.0.0.0, Culture=neutral, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\Refractored.MvvmHelpers.1.6.2\lib\net461\MvvmHelpers.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Management.Automation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\Microsoft.PowerShell.5.ReferenceAssemblies.1.1.0\lib\net4\System.Management.Automation.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Numerics" />
|
||||
<Reference Include="System.Numerics.Vectors, Version=4.1.4.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\System.Numerics.Vectors.4.5.0\lib\net46\System.Numerics.Vectors.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.ValueTuple, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\System.ValueTuple.4.5.0\lib\net461\System.ValueTuple.dll</HintPath>
|
||||
</Reference>
|
||||
<Reference Include="System.Xml" />
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Xml.Linq" />
|
||||
<Reference Include="System.Data.DataSetExtensions" />
|
||||
<Reference Include="System.Net.Http" />
|
||||
<Reference Include="System.Xaml">
|
||||
<RequiredTargetFramework>4.0</RequiredTargetFramework>
|
||||
</Reference>
|
||||
<Reference Include="WindowsBase" />
|
||||
<Reference Include="PresentationCore" />
|
||||
<Reference Include="PresentationFramework" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ApplicationDefinition Include="App.xaml">
|
||||
<Generator>MSBuild:Compile</Generator>
|
||||
<SubType>Designer</SubType>
|
||||
</ApplicationDefinition>
|
||||
<Compile Include="Extensions.cs" />
|
||||
<Compile Include="RelayCommand.cs" />
|
||||
<Compile Include="SimpleScriptRunner.cs" />
|
||||
<Page Include="MainWindow.xaml">
|
||||
<Generator>MSBuild:Compile</Generator>
|
||||
<SubType>Designer</SubType>
|
||||
</Page>
|
||||
<Compile Include="App.xaml.cs">
|
||||
<DependentUpon>App.xaml</DependentUpon>
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Include="MainWindow.xaml.cs">
|
||||
<DependentUpon>MainWindow.xaml</DependentUpon>
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="Properties\AssemblyInfo.cs">
|
||||
<SubType>Code</SubType>
|
||||
</Compile>
|
||||
<Compile Include="Properties\Resources.Designer.cs">
|
||||
<AutoGen>True</AutoGen>
|
||||
<DesignTime>True</DesignTime>
|
||||
<DependentUpon>Resources.resx</DependentUpon>
|
||||
</Compile>
|
||||
<Compile Include="Properties\Settings.Designer.cs">
|
||||
<AutoGen>True</AutoGen>
|
||||
<DependentUpon>Settings.settings</DependentUpon>
|
||||
<DesignTimeSharedInput>True</DesignTimeSharedInput>
|
||||
</Compile>
|
||||
<EmbeddedResource Include="Properties\Resources.resx">
|
||||
<Generator>ResXFileCodeGenerator</Generator>
|
||||
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
|
||||
</EmbeddedResource>
|
||||
<None Include="packages.config" />
|
||||
<None Include="Properties\Settings.settings">
|
||||
<Generator>SettingsSingleFileGenerator</Generator>
|
||||
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
|
||||
</None>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="App.config" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
</Project>
|
|
@ -0,0 +1,55 @@
|
|||
using System.Reflection;
|
||||
using System.Resources;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
using System.Windows;
|
||||
|
||||
// General Information about an assembly is controlled through the following
|
||||
// set of attributes. Change these attribute values to modify the information
|
||||
// associated with an assembly.
|
||||
[assembly: AssemblyTitle("MyLLDP")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("MyLLDP")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2020")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// Setting ComVisible to false makes the types in this assembly not visible
|
||||
// to COM components. If you need to access a type in this assembly from
|
||||
// COM, set the ComVisible attribute to true on that type.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
//In order to begin building localizable applications, set
|
||||
//<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file
|
||||
//inside a <PropertyGroup>. For example, if you are using US english
|
||||
//in your source files, set the <UICulture> to en-US. Then uncomment
|
||||
//the NeutralResourceLanguage attribute below. Update the "en-US" in
|
||||
//the line below to match the UICulture setting in the project file.
|
||||
|
||||
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
|
||||
|
||||
|
||||
[assembly: ThemeInfo(
|
||||
ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
|
||||
//(used if a resource is not found in the page,
|
||||
// or application resource dictionaries)
|
||||
ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
|
||||
//(used if a resource is not found in the page,
|
||||
// app, or any theme specific resource dictionaries)
|
||||
)]
|
||||
|
||||
|
||||
// Version information for an assembly consists of the following four values:
|
||||
//
|
||||
// Major Version
|
||||
// Minor Version
|
||||
// Build Number
|
||||
// Revision
|
||||
//
|
||||
// You can specify all the values or you can default the Build and Revision Numbers
|
||||
// by using the '*' as shown below:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("1.0.0.0")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.0")]
|
|
@ -0,0 +1,107 @@
|
|||
//------------------------------------------------------------------------------
|
||||
// <auto-generated>
|
||||
// This code was generated by a tool.
|
||||
// Runtime Version:4.0.30319.42000
|
||||
//
|
||||
// Changes to this file may cause incorrect behavior and will be lost if
|
||||
// the code is regenerated.
|
||||
// </auto-generated>
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
namespace MyLLDP.Properties {
|
||||
using System;
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// A strongly-typed resource class, for looking up localized strings, etc.
|
||||
/// </summary>
|
||||
// This class was auto-generated by the StronglyTypedResourceBuilder
|
||||
// class via a tool like ResGen or Visual Studio.
|
||||
// To add or remove a member, edit your .ResX file then rerun ResGen
|
||||
// with the /str option, or rebuild your VS project.
|
||||
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
|
||||
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
|
||||
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
|
||||
internal class Resources {
|
||||
|
||||
private static global::System.Resources.ResourceManager resourceMan;
|
||||
|
||||
private static global::System.Globalization.CultureInfo resourceCulture;
|
||||
|
||||
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
|
||||
internal Resources() {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns the cached ResourceManager instance used by this class.
|
||||
/// </summary>
|
||||
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
|
||||
internal static global::System.Resources.ResourceManager ResourceManager {
|
||||
get {
|
||||
if (object.ReferenceEquals(resourceMan, null)) {
|
||||
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("MyLLDP.Properties.Resources", typeof(Resources).Assembly);
|
||||
resourceMan = temp;
|
||||
}
|
||||
return resourceMan;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Overrides the current thread's CurrentUICulture property for all
|
||||
/// resource lookups using this strongly typed resource class.
|
||||
/// </summary>
|
||||
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
|
||||
internal static global::System.Globalization.CultureInfo Culture {
|
||||
get {
|
||||
return resourceCulture;
|
||||
}
|
||||
set {
|
||||
resourceCulture = value;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to #region classes
|
||||
///class DiscoveryProtocolPacket
|
||||
///{
|
||||
/// [string]$MachineName
|
||||
/// [datetime]$TimeCreated
|
||||
/// [int]$FragmentSize
|
||||
/// [byte[]]$Fragment
|
||||
///
|
||||
/// DiscoveryProtocolPacket([string]$MachineName, [datetime]$TimeCreated, [int]$FragmentSize, [byte[]]$Fragment)
|
||||
/// {
|
||||
/// $this.MachineName = $MachineName
|
||||
/// $this.TimeCreated = $TimeCreated
|
||||
/// $this.FragmentSize = $FragmentSize
|
||||
/// $this.Fragment = $Fragment
|
||||
///
|
||||
/// Add-Member -InputObject $this -MemberType ScriptProperty [rest of string was truncated]";.
|
||||
/// </summary>
|
||||
internal static string script1 {
|
||||
get {
|
||||
return ResourceManager.GetString("script1", resourceCulture);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to $capture = Invoke-DiscoveryProtocolCapture -Type LLDP
|
||||
///
|
||||
///Write-Host "Capture complete, parsing".
|
||||
/// </summary>
|
||||
internal static string script2 {
|
||||
get {
|
||||
return ResourceManager.GetString("script2", resourceCulture);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Looks up a localized string similar to ConvertFrom-LLDPPacket -Packet $capture | Out-String.
|
||||
/// </summary>
|
||||
internal static string script3 {
|
||||
get {
|
||||
return ResourceManager.GetString("script3", resourceCulture);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,903 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<root>
|
||||
<!--
|
||||
Microsoft ResX Schema
|
||||
|
||||
Version 2.0
|
||||
|
||||
The primary goals of this format is to allow a simple XML format
|
||||
that is mostly human readable. The generation and parsing of the
|
||||
various data types are done through the TypeConverter classes
|
||||
associated with the data types.
|
||||
|
||||
Example:
|
||||
|
||||
... ado.net/XML headers & schema ...
|
||||
<resheader name="resmimetype">text/microsoft-resx</resheader>
|
||||
<resheader name="version">2.0</resheader>
|
||||
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
|
||||
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
|
||||
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
|
||||
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
|
||||
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
|
||||
<value>[base64 mime encoded serialized .NET Framework object]</value>
|
||||
</data>
|
||||
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
|
||||
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
|
||||
<comment>This is a comment</comment>
|
||||
</data>
|
||||
|
||||
There are any number of "resheader" rows that contain simple
|
||||
name/value pairs.
|
||||
|
||||
Each data row contains a name, and value. The row also contains a
|
||||
type or mimetype. Type corresponds to a .NET class that support
|
||||
text/value conversion through the TypeConverter architecture.
|
||||
Classes that don't support this are serialized and stored with the
|
||||
mimetype set.
|
||||
|
||||
The mimetype is used for serialized objects, and tells the
|
||||
ResXResourceReader how to depersist the object. This is currently not
|
||||
extensible. For a given mimetype the value must be set accordingly:
|
||||
|
||||
Note - application/x-microsoft.net.object.binary.base64 is the format
|
||||
that the ResXResourceWriter will generate, however the reader can
|
||||
read any of the formats listed below.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.binary.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.soap.base64
|
||||
value : The object must be serialized with
|
||||
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
|
||||
: and then encoded with base64 encoding.
|
||||
|
||||
mimetype: application/x-microsoft.net.object.bytearray.base64
|
||||
value : The object must be serialized into a byte array
|
||||
: using a System.ComponentModel.TypeConverter
|
||||
: and then encoded with base64 encoding.
|
||||
-->
|
||||
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
|
||||
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
|
||||
<xsd:element name="root" msdata:IsDataSet="true">
|
||||
<xsd:complexType>
|
||||
<xsd:choice maxOccurs="unbounded">
|
||||
<xsd:element name="metadata">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" use="required" type="xsd:string" />
|
||||
<xsd:attribute name="type" type="xsd:string" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="assembly">
|
||||
<xsd:complexType>
|
||||
<xsd:attribute name="alias" type="xsd:string" />
|
||||
<xsd:attribute name="name" type="xsd:string" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="data">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
|
||||
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
|
||||
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
|
||||
<xsd:attribute ref="xml:space" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
<xsd:element name="resheader">
|
||||
<xsd:complexType>
|
||||
<xsd:sequence>
|
||||
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
|
||||
</xsd:sequence>
|
||||
<xsd:attribute name="name" type="xsd:string" use="required" />
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:choice>
|
||||
</xsd:complexType>
|
||||
</xsd:element>
|
||||
</xsd:schema>
|
||||
<resheader name="resmimetype">
|
||||
<value>text/microsoft-resx</value>
|
||||
</resheader>
|
||||
<resheader name="version">
|
||||
<value>2.0</value>
|
||||
</resheader>
|
||||
<resheader name="reader">
|
||||
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<resheader name="writer">
|
||||
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
|
||||
</resheader>
|
||||
<data name="script1" xml:space="preserve">
|
||||
<value>#region classes
|
||||
class DiscoveryProtocolPacket
|
||||
{
|
||||
[string]$MachineName
|
||||
[datetime]$TimeCreated
|
||||
[int]$FragmentSize
|
||||
[byte[]]$Fragment
|
||||
|
||||
DiscoveryProtocolPacket([string]$MachineName, [datetime]$TimeCreated, [int]$FragmentSize, [byte[]]$Fragment)
|
||||
{
|
||||
$this.MachineName = $MachineName
|
||||
$this.TimeCreated = $TimeCreated
|
||||
$this.FragmentSize = $FragmentSize
|
||||
$this.Fragment = $Fragment
|
||||
|
||||
Add-Member -InputObject $this -MemberType ScriptProperty -Name IsDiscoveryProtocolPacket -Value {
|
||||
if (
|
||||
[UInt16]0x2000 -eq [BitConverter]::ToUInt16($this.Fragment[21..20], 0) -or
|
||||
[UInt16]0x88CC -eq [BitConverter]::ToUInt16($this.Fragment[13..12], 0)
|
||||
) { return [bool]$true } else { return [bool]$false }
|
||||
}
|
||||
|
||||
Add-Member -InputObject $this -MemberType ScriptProperty -Name DiscoveryProtocolType -Value {
|
||||
if ([UInt16]0x2000 -eq [BitConverter]::ToUInt16($this.Fragment[21..20], 0)) {
|
||||
return [string]'CDP'
|
||||
}
|
||||
elseif ([UInt16]0x88CC -eq [BitConverter]::ToUInt16($this.Fragment[13..12], 0)) {
|
||||
return [string]'LLDP'
|
||||
}
|
||||
else {
|
||||
return [string]::Empty
|
||||
}
|
||||
}
|
||||
|
||||
Add-Member -InputObject $this -MemberType ScriptProperty -Name SourceAddress -Value {
|
||||
[PhysicalAddress]::new($this.Fragment[6..11]).ToString()
|
||||
}
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region function Invoke-DiscoveryProtocolCapture
|
||||
function Invoke-DiscoveryProtocolCapture {
|
||||
|
||||
<#
|
||||
|
||||
.SYNOPSIS
|
||||
|
||||
Capture CDP or LLDP packets on local or remote computers
|
||||
|
||||
.DESCRIPTION
|
||||
|
||||
Capture discovery protocol packets on local or remote computers. This function will start a packet capture and save the
|
||||
captured packets in a temporary ETL file. Only the first discovery protocol packet in the ETL file will be returned.
|
||||
|
||||
Cisco devices will by default send CDP announcements every 60 seconds. Default interval for LLDP packets is 30 seconds.
|
||||
|
||||
Requires elevation (Run as Administrator).
|
||||
WinRM and PowerShell remoting must be enabled on the target computer.
|
||||
|
||||
.PARAMETER ComputerName
|
||||
|
||||
Specifies one or more computers on which to capture packets. Defaults to $env:COMPUTERNAME.
|
||||
|
||||
.PARAMETER Duration
|
||||
|
||||
Specifies the duration for which the discovery protocol packets are captured, in seconds.
|
||||
|
||||
If Type is LLDP, Duration defaults to 32. If Type is CDP or omitted, Duration defaults to 62.
|
||||
|
||||
.PARAMETER Type
|
||||
|
||||
Specifies what type of packet to capture, CDP or LLDP. If omitted, both types will be captured,
|
||||
but only the first one will be returned.
|
||||
|
||||
If Type is LLDP, Duration defaults to 32. If Type is CDP or omitted, Duration defaults to 62.
|
||||
|
||||
.OUTPUTS
|
||||
|
||||
DiscoveryProtocolPacket
|
||||
|
||||
.EXAMPLE
|
||||
|
||||
PS C:\> $Packet = Invoke-DiscoveryProtocolCapture -Type CDP -Duration 60
|
||||
PS C:\> Get-DiscoveryProtocolData -Packet $Packet
|
||||
|
||||
Port : FastEthernet0/1
|
||||
Device : SWITCH1.domain.example
|
||||
Model : cisco WS-C2960-48TT-L
|
||||
IPAddress : 192.0.2.10
|
||||
VLAN : 10
|
||||
Computer : COMPUTER1
|
||||
Type : CDP
|
||||
|
||||
.EXAMPLE
|
||||
|
||||
PS C:\> Invoke-DiscoveryProtocolCapture -Computer COMPUTER1 | Get-DiscoveryProtocolData
|
||||
|
||||
Port : FastEthernet0/1
|
||||
Device : SWITCH1.domain.example
|
||||
Model : cisco WS-C2960-48TT-L
|
||||
IPAddress : 192.0.2.10
|
||||
VLAN : 10
|
||||
Computer : COMPUTER1
|
||||
Type : CDP
|
||||
|
||||
.EXAMPLE
|
||||
|
||||
PS C:\> 'COMPUTER1', 'COMPUTER2' | Invoke-DiscoveryProtocolCapture | Get-DiscoveryProtocolData
|
||||
|
||||
Port : FastEthernet0/1
|
||||
Device : SWITCH1.domain.example
|
||||
Model : cisco WS-C2960-48TT-L
|
||||
IPAddress : 192.0.2.10
|
||||
VLAN : 10
|
||||
Computer : COMPUTER1
|
||||
Type : CDP
|
||||
|
||||
Port : FastEthernet0/2
|
||||
Device : SWITCH1.domain.example
|
||||
Model : cisco WS-C2960-48TT-L
|
||||
IPAddress : 192.0.2.10
|
||||
VLAN : 20
|
||||
Computer : COMPUTER2
|
||||
Type : CDP
|
||||
|
||||
#>
|
||||
|
||||
[CmdletBinding()]
|
||||
[OutputType('DiscoveryProtocolPacket')]
|
||||
[Alias('Capture-CDPPacket', 'Capture-LLDPPacket')]
|
||||
param(
|
||||
[Parameter(Position=0,
|
||||
ValueFromPipeline=$true,
|
||||
ValueFromPipelineByPropertyName=$true)]
|
||||
[Alias('CN', 'Computer')]
|
||||
[String[]]$ComputerName = $env:COMPUTERNAME,
|
||||
|
||||
[Parameter(Position=1)]
|
||||
[Int16]$Duration = $(if ($Type -eq 'LLDP') { 32 } else { 62 }),
|
||||
|
||||
[Parameter(Position=2)]
|
||||
[ValidateSet('CDP', 'LLDP')]
|
||||
[String]$Type
|
||||
)
|
||||
|
||||
begin {
|
||||
$Identity = [Security.Principal.WindowsIdentity]::GetCurrent()
|
||||
$Principal = New-Object Security.Principal.WindowsPrincipal $Identity
|
||||
if (-not $Principal.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)) {
|
||||
throw 'Invoke-DiscoveryProtocolCapture requires elevation. Please run PowerShell as administrator.'
|
||||
}
|
||||
|
||||
if ($MyInvocation.InvocationName -ne $MyInvocation.MyCommand) {
|
||||
if ($MyInvocation.InvocationName -eq 'Capture-CDPPacket') { $Type = 'CDP' }
|
||||
if ($MyInvocation.InvocationName -eq 'Capture-LLDPPacket') { $Type = 'LLDP' }
|
||||
$Warning = '{0} has been deprecated, please use {1}' -f $MyInvocation.InvocationName, $MyInvocation.MyCommand
|
||||
Write-Warning $Warning
|
||||
}
|
||||
}
|
||||
|
||||
process {
|
||||
|
||||
foreach ($Computer in $ComputerName) {
|
||||
|
||||
$sessionParam = @{
|
||||
'Verbose'=$VerbosePreference
|
||||
}
|
||||
|
||||
$cimParam = @{
|
||||
'Verbose'=$VerbosePreference
|
||||
}
|
||||
|
||||
$CimSession = $null
|
||||
try {
|
||||
#$CimSession = New-CimSession -ComputerName $Computer -ErrorAction Stop
|
||||
} catch {
|
||||
#Write-Warning "Unable to create CimSession. Please make sure WinRM and PSRemoting is enabled on $Computer."
|
||||
#continue
|
||||
}
|
||||
|
||||
if ($CimSession) {
|
||||
$cimParam.Add('CimSession',$CimSession)
|
||||
}
|
||||
|
||||
$PSSession = $null
|
||||
if ($Computer -notlike $env:COMPUTERNAME) {
|
||||
New-PSSession -ComputerName $Computer
|
||||
}
|
||||
if ($PSSession) {
|
||||
$sessionParam.Add('Session',$PSSession)
|
||||
}
|
||||
|
||||
$ETLFilePath = Invoke-Command @sessionParam -ScriptBlock {
|
||||
$TempFile = New-TemporaryFile
|
||||
$ETLFile = Rename-Item -Path $TempFile.FullName -NewName $TempFile.FullName.Replace('.tmp', '.etl') -PassThru
|
||||
$ETLFile.FullName
|
||||
}
|
||||
|
||||
$Adapter = Get-NetAdapter @cimParam -Physical |
|
||||
Where-Object {$_.Status -eq 'Up' -and $_.InterfaceType -eq 6} |
|
||||
Select-Object -First 1 Name, MacAddress
|
||||
|
||||
$MACAddress = [PhysicalAddress]::Parse($Adapter.MacAddress).ToString()
|
||||
|
||||
if ($Adapter) {
|
||||
$SessionName = 'Capture-{0}' -f (Get-Date).ToString('s')
|
||||
New-NetEventSession -Name $SessionName -LocalFilePath $ETLFilePath -CaptureMode SaveToFile @cimParam | Out-Null
|
||||
|
||||
$LinkLayerAddress = switch ($Type) {
|
||||
'CDP' { '01-00-0c-cc-cc-cc' }
|
||||
'LLDP' { '01-80-c2-00-00-0e', '01-80-c2-00-00-03', '01-80-c2-00-00-00' }
|
||||
Default { '01-00-0c-cc-cc-cc', '01-80-c2-00-00-0e', '01-80-c2-00-00-03', '01-80-c2-00-00-00' }
|
||||
}
|
||||
|
||||
$PacketCaptureParams = @{
|
||||
SessionName = $SessionName
|
||||
TruncationLength = 0
|
||||
CaptureType = 'Physical'
|
||||
LinkLayerAddress = $LinkLayerAddress
|
||||
}
|
||||
if ($CimSession) {
|
||||
$PacketCaptureParams.Add('CimSession', $CimSession)
|
||||
}
|
||||
|
||||
Add-NetEventPacketCaptureProvider @PacketCaptureParams | Out-Null
|
||||
Add-NetEventNetworkAdapter -Name $Adapter.Name -PromiscuousMode $True @cimParam | Out-Null
|
||||
|
||||
Start-NetEventSession -Name $SessionName @cimParam
|
||||
|
||||
$Seconds = $Duration
|
||||
$End = (Get-Date).AddSeconds($Seconds)
|
||||
while ($End -gt (Get-Date)) {
|
||||
$SecondsLeft = $End.Subtract((Get-Date)).TotalSeconds
|
||||
$Percent = ($Seconds - $SecondsLeft) / $Seconds * 100
|
||||
Write-Progress -Activity "Discovery Protocol Packet Capture" -Status "Capturing on $Computer..." -SecondsRemaining $SecondsLeft -PercentComplete $Percent
|
||||
[System.Threading.Thread]::Sleep(500)
|
||||
}
|
||||
|
||||
Stop-NetEventSession -Name $SessionName @cimParam
|
||||
|
||||
$Events = Invoke-Command @sessionParam -ScriptBlock {
|
||||
$Events = Get-WinEvent -Path $ETLFilePath -Oldest -FilterXPath "*[System[EventID=1001]]"
|
||||
|
||||
[string[]]$XpathQueries = @(
|
||||
"Event/EventData/Data[@Name='FragmentSize']"
|
||||
"Event/EventData/Data[@Name='Fragment']"
|
||||
)
|
||||
|
||||
$PropertySelector = [System.Diagnostics.Eventing.Reader.EventLogPropertySelector]::new($XpathQueries)
|
||||
|
||||
foreach ($Event in $Events) {
|
||||
$EventData = $Event | Select-Object MachineName, TimeCreated
|
||||
$EventData | Add-Member -NotePropertyName FragmentSize -NotePropertyValue $null
|
||||
$EventData | Add-Member -NotePropertyName Fragment -NotePropertyValue $null
|
||||
$EventData.FragmentSize, $EventData.Fragment = $Event.GetPropertyValues($PropertySelector)
|
||||
$EventData
|
||||
}
|
||||
}
|
||||
|
||||
$FoundPacket = $null
|
||||
|
||||
foreach ($Event in $Events) {
|
||||
$Packet = [DiscoveryProtocolPacket]::new(
|
||||
$Event.MachineName,
|
||||
$Event.TimeCreated,
|
||||
$Event.FragmentSize,
|
||||
$Event.Fragment
|
||||
)
|
||||
|
||||
if ($Packet.IsDiscoveryProtocolPacket -and $Packet.SourceAddress -ne $MACAddress) {
|
||||
$FoundPacket = $Packet
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
Remove-NetEventSession -Name $SessionName @cimParam
|
||||
|
||||
Invoke-Command @sessionParam -ScriptBlock {
|
||||
Remove-Item -Path $ETLFilePath -Force
|
||||
}
|
||||
|
||||
if ($PSSession) {
|
||||
Remove-PSSession @sessionParam
|
||||
}
|
||||
|
||||
if ($FoundPacket) {
|
||||
$FoundPacket
|
||||
} else {
|
||||
Write-Warning "No discovery protocol packets captured on $Computer in $Seconds seconds."
|
||||
return
|
||||
}
|
||||
} else {
|
||||
Write-Warning "Unable to find a connected wired adapter on $Computer."
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
end {}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region function Get-DiscoveryProtocolData
|
||||
function Get-DiscoveryProtocolData {
|
||||
|
||||
<#
|
||||
|
||||
.SYNOPSIS
|
||||
|
||||
Parse CDP or LLDP packets captured by Invoke-DiscoveryProtocolCapture
|
||||
|
||||
.DESCRIPTION
|
||||
|
||||
Gets computername, type and packet details from a DiscoveryProtocolPacket.
|
||||
|
||||
Calls ConvertFrom-CDPPacket or ConvertFrom-LLDPPacket to extract packet details
|
||||
from a byte array.
|
||||
|
||||
.PARAMETER Packet
|
||||
|
||||
Specifies an object of type DiscoveryProtocolPacket.
|
||||
|
||||
.EXAMPLE
|
||||
|
||||
PS C:\> $Packet = Invoke-DiscoveryProtocolCapture
|
||||
PS C:\> Get-DiscoveryProtocolData -Packet $Packet
|
||||
|
||||
Port : FastEthernet0/1
|
||||
Device : SWITCH1.domain.example
|
||||
Model : cisco WS-C2960-48TT-L
|
||||
IPAddress : 192.0.2.10
|
||||
VLAN : 10
|
||||
Computer : COMPUTER1
|
||||
Type : CDP
|
||||
|
||||
.EXAMPLE
|
||||
|
||||
PS C:\> Invoke-DiscoveryProtocolCapture -Computer COMPUTER1 | Get-DiscoveryProtocolData
|
||||
|
||||
Port : FastEthernet0/1
|
||||
Device : SWITCH1.domain.example
|
||||
Model : cisco WS-C2960-48TT-L
|
||||
IPAddress : 192.0.2.10
|
||||
VLAN : 10
|
||||
Computer : COMPUTER1
|
||||
Type : CDP
|
||||
|
||||
.EXAMPLE
|
||||
|
||||
PS C:\> 'COMPUTER1', 'COMPUTER2' | Invoke-DiscoveryProtocolCapture | Get-DiscoveryProtocolData
|
||||
|
||||
Port : FastEthernet0/1
|
||||
Device : SWITCH1.domain.example
|
||||
Model : cisco WS-C2960-48TT-L
|
||||
IPAddress : 192.0.2.10
|
||||
VLAN : 10
|
||||
Computer : COMPUTER1
|
||||
Type : CDP
|
||||
|
||||
Port : FastEthernet0/2
|
||||
Device : SWITCH1.domain.example
|
||||
Model : cisco WS-C2960-48TT-L
|
||||
IPAddress : 192.0.2.10
|
||||
VLAN : 20
|
||||
Computer : COMPUTER2
|
||||
Type : CDP
|
||||
|
||||
#>
|
||||
|
||||
[CmdletBinding()]
|
||||
[Alias('Parse-CDPPacket', 'Parse-LLDPPacket')]
|
||||
param(
|
||||
[Parameter(Position=0,
|
||||
Mandatory=$true,
|
||||
ValueFromPipeline=$true,
|
||||
ValueFromPipelineByPropertyName=$true)]
|
||||
[DiscoveryProtocolPacket[]]
|
||||
$Packet
|
||||
)
|
||||
|
||||
begin {
|
||||
if ($MyInvocation.InvocationName -ne $MyInvocation.MyCommand) {
|
||||
$Warning = '{0} has been deprecated, please use {1}' -f $MyInvocation.InvocationName, $MyInvocation.MyCommand
|
||||
Write-Warning $Warning
|
||||
}
|
||||
}
|
||||
|
||||
process {
|
||||
foreach ($item in $Packet) {
|
||||
switch ($item.DiscoveryProtocolType) {
|
||||
'CDP' { $PacketData = ConvertFrom-CDPPacket -Packet $item.Fragment }
|
||||
'LLDP' { $PacketData = ConvertFrom-LLDPPacket -Packet $item.Fragment }
|
||||
Default { throw 'No valid CDP or LLDP found in $Packet' }
|
||||
}
|
||||
|
||||
$PacketData | Add-Member -NotePropertyName Computer -NotePropertyValue $item.MachineName
|
||||
$PacketData | Add-Member -NotePropertyName Type -NotePropertyValue $item.DiscoveryProtocolType
|
||||
$PacketData
|
||||
}
|
||||
}
|
||||
|
||||
end {}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region function ConvertFrom-CDPPacket
|
||||
function ConvertFrom-CDPPacket {
|
||||
|
||||
<#
|
||||
|
||||
.SYNOPSIS
|
||||
|
||||
Parse CDP packet.
|
||||
|
||||
.DESCRIPTION
|
||||
|
||||
Parse CDP packet to get port, device, model, ipaddress and vlan.
|
||||
|
||||
This function is used by Get-DiscoveryProtocolData to parse the
|
||||
Fragment property of a DiscoveryProtocolPacket object.
|
||||
|
||||
.PARAMETER Packet
|
||||
|
||||
Raw CDP packet as byte array.
|
||||
|
||||
This function is used by Get-DiscoveryProtocolData to parse the
|
||||
Fragment property of a DiscoveryProtocolPacket object.
|
||||
|
||||
.EXAMPLE
|
||||
|
||||
PS C:\> $Packet = Invoke-DiscoveryProtocolCapture -Type CDP
|
||||
PS C:\> ConvertFrom-CDPPacket -Packet $Packet.Fragment
|
||||
|
||||
Port : FastEthernet0/1
|
||||
Device : SWITCH1.domain.example
|
||||
Model : cisco WS-C2960-48TT-L
|
||||
IPAddress : 192.0.2.10
|
||||
VLAN : 10
|
||||
|
||||
#>
|
||||
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Position=0,
|
||||
Mandatory=$true)]
|
||||
[byte[]]$Packet
|
||||
)
|
||||
|
||||
begin {}
|
||||
|
||||
process {
|
||||
|
||||
$Offset = 26
|
||||
$Hash = @{}
|
||||
|
||||
while ($Offset -lt ($Packet.Length - 4)) {
|
||||
|
||||
$Type = [BitConverter]::ToUInt16($Packet[($Offset + 1)..$Offset], 0)
|
||||
$Length = [BitConverter]::ToUInt16($Packet[($Offset + 3)..($Offset + 2)], 0)
|
||||
|
||||
switch ($Type)
|
||||
{
|
||||
1 { $Hash.Add('Device', [System.Text.Encoding]::ASCII.GetString($Packet[($Offset + 4)..($Offset + $Length)])) }
|
||||
3 { $Hash.Add('Port', [System.Text.Encoding]::ASCII.GetString($Packet[($Offset + 4)..($Offset + $Length)])) }
|
||||
6 { $Hash.Add('Model', [System.Text.Encoding]::ASCII.GetString($Packet[($Offset + 4)..($Offset + $Length)])) }
|
||||
10 { $Hash.Add('VLAN', [BitConverter]::ToUInt16($Packet[($Offset + 5)..($Offset + 4)], 0)) }
|
||||
22 { $Hash.Add('IPAddress', ([System.Net.IPAddress][byte[]]$Packet[($Offset + 13)..($Offset + 16)]).IPAddressToString) }
|
||||
}
|
||||
|
||||
if ($Length -eq 0 ) {
|
||||
$Offset = $Packet.Length
|
||||
}
|
||||
|
||||
$Offset = $Offset + $Length
|
||||
|
||||
}
|
||||
|
||||
return [PSCustomObject]$Hash
|
||||
|
||||
}
|
||||
|
||||
end {}
|
||||
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region function ConvertFrom-LLDPPacket
|
||||
function ConvertFrom-LLDPPacket {
|
||||
|
||||
<#
|
||||
|
||||
.SYNOPSIS
|
||||
|
||||
Parse LLDP packet.
|
||||
|
||||
.DESCRIPTION
|
||||
|
||||
Parse LLDP packet to get port, description, device, model, ipaddress and vlan.
|
||||
|
||||
.PARAMETER Packet
|
||||
|
||||
Raw LLDP packet as byte array.
|
||||
|
||||
This function is used by Get-DiscoveryProtocolData to parse the
|
||||
Fragment property of a DiscoveryProtocolPacket object.
|
||||
|
||||
.EXAMPLE
|
||||
|
||||
PS C:\> $Packet = Invoke-DiscoveryProtocolCapture -Type LLDP
|
||||
PS C:\> ConvertFrom-LLDPPacket -Packet $Packet.Fragment
|
||||
|
||||
Model : WS-C2960-48TT-L
|
||||
Description : HR Workstation
|
||||
VLAN : 10
|
||||
Port : Fa0/1
|
||||
Device : SWITCH1.domain.example
|
||||
IPAddress : 192.0.2.10
|
||||
|
||||
#>
|
||||
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Position=0,
|
||||
Mandatory=$true)]
|
||||
[byte[]]$Packet
|
||||
)
|
||||
|
||||
begin {
|
||||
$TlvType = @{
|
||||
PortId = 2
|
||||
PortDescription = 4
|
||||
SystemName = 5
|
||||
ManagementAddress = 8
|
||||
OrganizationSpecific = 127
|
||||
}
|
||||
}
|
||||
|
||||
process {
|
||||
|
||||
$Destination = [PhysicalAddress]::new($Packet[0..5])
|
||||
$Source = [PhysicalAddress]::new($Packet[6..11])
|
||||
$LLDP = [BitConverter]::ToUInt16($Packet[13..12], 0)
|
||||
|
||||
Write-Verbose "Destination: $Destination"
|
||||
Write-Verbose "Source: $Source"
|
||||
Write-Verbose "LLDP: $LLDP"
|
||||
|
||||
$Offset = 14
|
||||
$Mask = 0x01FF
|
||||
$Hash = @{}
|
||||
|
||||
while ($Offset -lt $Packet.Length)
|
||||
{
|
||||
$Type = $Packet[$Offset] -shr 1
|
||||
$Length = [BitConverter]::ToUInt16($Packet[($Offset + 1)..$Offset], 0) -band $Mask
|
||||
$Offset += 2
|
||||
|
||||
switch ($Type)
|
||||
{
|
||||
$TlvType.PortId {
|
||||
$Subtype = $Packet[($Offset)]
|
||||
|
||||
if ($SubType -in (1, 2, 5, 6, 7)) {
|
||||
$Hash.Add('Port', [System.Text.Encoding]::ASCII.GetString($Packet[($Offset + 1)..($Offset + $Length - 1)]))
|
||||
}
|
||||
|
||||
if ($Subtype -eq 3) {
|
||||
$Hash.Add('Port', [PhysicalAddress]::new($Packet[($Offset + 1)..($Offset + $Length - 1)]))
|
||||
}
|
||||
|
||||
$Offset += $Length
|
||||
break
|
||||
}
|
||||
|
||||
$TlvType.PortDescription {
|
||||
$Hash.Add('Description', [System.Text.Encoding]::ASCII.GetString($Packet[$Offset..($Offset + $Length - 1)]))
|
||||
$Offset += $Length
|
||||
break
|
||||
}
|
||||
|
||||
$TlvType.SystemName {
|
||||
$Hash.Add('Device', [System.Text.Encoding]::ASCII.GetString($Packet[$Offset..($Offset + $Length - 1)]))
|
||||
$Offset += $Length
|
||||
break
|
||||
}
|
||||
|
||||
$TlvType.ManagementAddress {
|
||||
$AddrLen = $Packet[($Offset)]
|
||||
$Subtype = $Packet[($Offset + 1)]
|
||||
|
||||
if ($Subtype -eq 1)
|
||||
{
|
||||
$Hash.Add('IPAddress', ([System.Net.IPAddress][byte[]]$Packet[($Offset + 2)..($Offset + $AddrLen)]).IPAddressToString)
|
||||
}
|
||||
|
||||
$Offset += $Length
|
||||
break
|
||||
}
|
||||
|
||||
$TlvType.OrganizationSpecific {
|
||||
$OUI = [System.BitConverter]::ToString($Packet[($Offset)..($Offset + 2)])
|
||||
|
||||
if ($OUI -eq '00-12-BB') {
|
||||
$Subtype = $Packet[($Offset + 3)]
|
||||
if ($Subtype -eq 10) {
|
||||
$Hash.Add('Model', [System.Text.Encoding]::ASCII.GetString($Packet[($Offset + 4)..($Offset + $Length - 1)]))
|
||||
$Offset += $Length
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if ($OUI -eq '00-80-C2') {
|
||||
$Subtype = $Packet[($Offset + 3)]
|
||||
if ($Subtype -eq 1) {
|
||||
$Hash.Add('VLAN', [BitConverter]::ToUInt16($Packet[($Offset + 5)..($Offset + 4)], 0))
|
||||
$Offset += $Length
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
$Tlv = [PSCustomObject] @{
|
||||
Type = $Type
|
||||
Value = [System.Text.Encoding]::ASCII.GetString($Packet[$Offset..($Offset + $Length)])
|
||||
}
|
||||
Write-Verbose $Tlv
|
||||
$Offset += $Length
|
||||
break
|
||||
}
|
||||
|
||||
default {
|
||||
$Tlv = [PSCustomObject] @{
|
||||
Type = $Type
|
||||
Value = [System.Text.Encoding]::ASCII.GetString($Packet[$Offset..($Offset + $Length)])
|
||||
}
|
||||
Write-Verbose $Tlv
|
||||
$Offset += $Length
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
[PSCustomObject]$Hash
|
||||
}
|
||||
|
||||
end {}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region function Export-Pcap
|
||||
function Export-Pcap {
|
||||
|
||||
<#
|
||||
|
||||
.SYNOPSIS
|
||||
|
||||
Export packets to pcap
|
||||
|
||||
.DESCRIPTION
|
||||
|
||||
Export packets, captured using Invoke-DiscoveryProtocolCapture, to pcap format.
|
||||
|
||||
.PARAMETER Packet
|
||||
|
||||
Specifies one or more objects of type DiscoveryProtocolPacket.
|
||||
|
||||
.PARAMETER Path
|
||||
|
||||
Relative or absolute path to pcap file.
|
||||
|
||||
.PARAMETER Invoke
|
||||
|
||||
If Invoke is set, exported file is opened in the program associated with pcap files.
|
||||
|
||||
.EXAMPLE
|
||||
|
||||
PS C:\> $Packet = Invoke-DiscoveryProtocolCapture
|
||||
PS C:\> Export-Pcap -Packet $Packet -Path C:\Windows\Temp\captures.pcap -Invoke
|
||||
|
||||
Export captured packet to C:\Windows\Temp\captures.pcap and open file in
|
||||
the program associated with pcap files.
|
||||
|
||||
.EXAMPLE
|
||||
|
||||
PS C:\> 'COMPUTER1', 'COMPUTER2' | Invoke-DiscoveryProtocolCapture | Export-Pcap -Path captures.pcap
|
||||
|
||||
Export captured packets to captures.pcap in current directory. Export-Pcap supports input from pipeline.
|
||||
|
||||
#>
|
||||
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[Parameter(Mandatory=$true,
|
||||
ValueFromPipeline=$true,
|
||||
ValueFromPipelineByPropertyName=$true)]
|
||||
[DiscoveryProtocolPacket[]]$Packet,
|
||||
|
||||
[Parameter(Mandatory=$true)]
|
||||
[ValidateScript({
|
||||
if ([System.IO.Path]::IsPathRooted($_)) {
|
||||
$AbsolutePath = $_
|
||||
} else {
|
||||
$AbsolutePath = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($_)
|
||||
}
|
||||
if (-not(Test-Path (Split-Path $AbsolutePath -Parent))) {
|
||||
throw "Folder does not exist"
|
||||
}
|
||||
if ($_ -notmatch '\.pcap$') {
|
||||
throw "Extension must be pcap"
|
||||
}
|
||||
return $true
|
||||
})]
|
||||
[System.IO.FileInfo]$Path,
|
||||
|
||||
[Parameter(Mandatory=$false)]
|
||||
[switch]$Invoke
|
||||
)
|
||||
|
||||
begin {
|
||||
[uint32]$magicNumber = '0xa1b2c3d4'
|
||||
[uint16]$versionMajor = 2
|
||||
[uint16]$versionMinor = 4
|
||||
[int32] $thisZone = 0
|
||||
[uint32]$sigFigs = 0
|
||||
[uint32]$snapLen = 65536
|
||||
[uint32]$network = 1
|
||||
|
||||
$stream = New-Object System.IO.MemoryStream
|
||||
$writer = New-Object System.IO.BinaryWriter $stream
|
||||
|
||||
$writer.Write($magicNumber)
|
||||
$writer.Write($versionMajor)
|
||||
$writer.Write($versionMinor)
|
||||
$writer.Write($thisZone)
|
||||
$writer.Write($sigFigs)
|
||||
$writer.Write($snapLen)
|
||||
$writer.Write($network)
|
||||
}
|
||||
|
||||
process {
|
||||
foreach ($item in $Packet) {
|
||||
[uint32]$tsSec = ([DateTimeOffset]$item.TimeCreated).ToUnixTimeSeconds()
|
||||
[uint32]$tsUsec = $item.TimeCreated.Millisecond
|
||||
[uint32]$inclLen = $item.FragmentSize
|
||||
[uint32]$origLen = $inclLen
|
||||
|
||||
$writer.Write($tsSec)
|
||||
$writer.Write($tsUsec)
|
||||
$writer.Write($inclLen)
|
||||
$writer.Write($origLen)
|
||||
$writer.Write($item.Fragment)
|
||||
}
|
||||
}
|
||||
|
||||
end {
|
||||
$bytes = $stream.ToArray()
|
||||
|
||||
$stream.Dispose()
|
||||
$writer.Dispose()
|
||||
|
||||
if (-not([System.IO.Path]::IsPathRooted($Path))) {
|
||||
$Path = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($Path)
|
||||
}
|
||||
|
||||
[System.IO.File]::WriteAllBytes($Path, $bytes)
|
||||
|
||||
if ($Invoke) {
|
||||
Invoke-Item -Path $Path
|
||||
}
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
"Starting capture for 60 seconds"</value>
|
||||
</data>
|
||||
<data name="script2" xml:space="preserve">
|
||||
<value>$capture = Invoke-DiscoveryProtocolCapture -Type LLDP
|
||||
|
||||
Write-Host "Capture complete, parsing"</value>
|
||||
</data>
|
||||
<data name="script3" xml:space="preserve">
|
||||
<value>ConvertFrom-LLDPPacket -Packet $capture | Out-String</value>
|
||||
</data>
|
||||
</root>
|
|
@ -0,0 +1,28 @@
|
|||
//------------------------------------------------------------------------------
|
||||
// <auto-generated>
|
||||
// This code was generated by a tool.
|
||||
// Runtime Version:4.0.30319.42000
|
||||
//
|
||||
// Changes to this file may cause incorrect behavior and will be lost if
|
||||
// the code is regenerated.
|
||||
// </auto-generated>
|
||||
//------------------------------------------------------------------------------
|
||||
|
||||
namespace MyLLDP.Properties
|
||||
{
|
||||
|
||||
|
||||
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
|
||||
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "11.0.0.0")]
|
||||
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
|
||||
{
|
||||
|
||||
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
|
||||
|
||||
public static Settings Default {
|
||||
get {
|
||||
return defaultInstance;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
<?xml version='1.0' encoding='utf-8'?>
|
||||
<SettingsFile xmlns="uri:settings" CurrentProfile="(Default)">
|
||||
<Profiles>
|
||||
<Profile Name="(Default)" />
|
||||
</Profiles>
|
||||
<Settings />
|
||||
</SettingsFile>
|
|
@ -0,0 +1,148 @@
|
|||
using System;
|
||||
using System.Diagnostics;
|
||||
using System.Windows.Input;
|
||||
|
||||
namespace SMM.Command
|
||||
{
|
||||
/// <summary>
|
||||
/// A command whose sole purpose is to
|
||||
/// relay its functionality to other
|
||||
/// objects by invoking delegates. The
|
||||
/// default return value for the CanExecute
|
||||
/// method is 'true'.
|
||||
/// </summary>
|
||||
internal class RelayCommand<T> : ICommand
|
||||
{
|
||||
#region Fields
|
||||
|
||||
readonly Action<T> _execute = null;
|
||||
readonly Predicate<T> _canExecute = null;
|
||||
|
||||
#endregion // Fields
|
||||
|
||||
#region Constructors
|
||||
|
||||
public RelayCommand(Action<T> execute)
|
||||
: this(execute, null)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new command.
|
||||
/// </summary>
|
||||
/// <param name="execute">The execution logic.</param>
|
||||
/// <param name="canExecute">The execution status logic.</param>
|
||||
public RelayCommand(Action<T> execute, Predicate<T> canExecute)
|
||||
{
|
||||
if (execute == null)
|
||||
throw new ArgumentNullException("execute");
|
||||
|
||||
_execute = execute;
|
||||
_canExecute = canExecute;
|
||||
}
|
||||
|
||||
#endregion // Constructors
|
||||
|
||||
#region ICommand Members
|
||||
|
||||
[DebuggerStepThrough]
|
||||
public bool CanExecute(object parameter)
|
||||
{
|
||||
return _canExecute == null ? true : _canExecute((T)parameter);
|
||||
}
|
||||
|
||||
public event EventHandler CanExecuteChanged
|
||||
{
|
||||
add
|
||||
{
|
||||
if (_canExecute != null)
|
||||
CommandManager.RequerySuggested += value;
|
||||
}
|
||||
remove
|
||||
{
|
||||
if (_canExecute != null)
|
||||
CommandManager.RequerySuggested -= value;
|
||||
}
|
||||
}
|
||||
|
||||
public void Execute(object parameter)
|
||||
{
|
||||
_execute((T)parameter);
|
||||
}
|
||||
|
||||
#endregion // ICommand Members
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A command whose sole purpose is to
|
||||
/// relay its functionality to other
|
||||
/// objects by invoking delegates. The
|
||||
/// default return value for the CanExecute
|
||||
/// method is 'true'.
|
||||
/// </summary>
|
||||
internal class RelayCommand : ICommand
|
||||
{
|
||||
#region Fields
|
||||
|
||||
readonly Action _execute;
|
||||
readonly Func<bool> _canExecute;
|
||||
|
||||
#endregion // Fields
|
||||
|
||||
#region Constructors
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new command that can always execute.
|
||||
/// </summary>
|
||||
/// <param name="execute">The execution logic.</param>
|
||||
public RelayCommand(Action execute)
|
||||
: this(execute, null)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Creates a new command.
|
||||
/// </summary>
|
||||
/// <param name="execute">The execution logic.</param>
|
||||
/// <param name="canExecute">The execution status logic.</param>
|
||||
public RelayCommand(Action execute, Func<bool> canExecute)
|
||||
{
|
||||
if (execute == null)
|
||||
throw new ArgumentNullException("execute");
|
||||
|
||||
_execute = execute;
|
||||
_canExecute = canExecute;
|
||||
}
|
||||
|
||||
#endregion // Constructors
|
||||
|
||||
#region ICommand Members
|
||||
|
||||
[DebuggerStepThrough]
|
||||
public bool CanExecute(object parameter)
|
||||
{
|
||||
return _canExecute == null ? true : _canExecute();
|
||||
}
|
||||
|
||||
public event EventHandler CanExecuteChanged
|
||||
{
|
||||
add
|
||||
{
|
||||
if (_canExecute != null)
|
||||
CommandManager.RequerySuggested += value;
|
||||
}
|
||||
remove
|
||||
{
|
||||
if (_canExecute != null)
|
||||
CommandManager.RequerySuggested -= value;
|
||||
}
|
||||
}
|
||||
|
||||
public void Execute(object parameter)
|
||||
{
|
||||
_execute();
|
||||
}
|
||||
|
||||
#endregion // ICommand Members
|
||||
}
|
||||
}
|
|
@ -0,0 +1,316 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Diagnostics;
|
||||
using System.Linq;
|
||||
using System.Management.Automation;
|
||||
using System.Management.Automation.Language;
|
||||
using System.Management.Automation.Runspaces;
|
||||
using System.Net;
|
||||
using System.Security.Principal;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
using MvvmHelpers;
|
||||
using SMM.Helper;
|
||||
|
||||
|
||||
namespace SMM.Automation
|
||||
{
|
||||
public class SimpleScriptRunner : BaseViewModel
|
||||
{
|
||||
#region fields
|
||||
|
||||
private object instanceLock = new object();
|
||||
private PowerShell currentPowerShell;
|
||||
private List<(string, object)> proxyVariables = new List<(string, object)>();
|
||||
internal string _source;
|
||||
|
||||
#endregion // fields
|
||||
|
||||
#region constructor
|
||||
|
||||
/// <summary>
|
||||
/// Constructs a script runner that can be used for execution of simple PowerShell fragements.
|
||||
/// </summary>
|
||||
/// <param name="ScriptSource"></param>
|
||||
public SimpleScriptRunner(string ScriptSource) {
|
||||
|
||||
currentPowerShell = PowerShell.Create();
|
||||
_source = ScriptSource;
|
||||
ScriptFragments.Add(ScriptBlock.Create(ScriptSource));
|
||||
}
|
||||
|
||||
~SimpleScriptRunner() {
|
||||
// Dispose the PowerShell object and set currentPowerShell to null.
|
||||
// It is locked because currentPowerShell may be accessed by the
|
||||
// ctrl-C handler.
|
||||
lock (instanceLock) {
|
||||
currentPowerShell.Runspace?.Dispose();
|
||||
currentPowerShell?.Dispose();
|
||||
currentPowerShell = null;
|
||||
}
|
||||
}
|
||||
|
||||
#endregion // constructor
|
||||
|
||||
#region properties
|
||||
|
||||
public int ExitCode { get; private set; } = 0;
|
||||
|
||||
public bool HadErrors => currentPowerShell?.HadErrors ?? false;
|
||||
|
||||
public Dictionary<string, object> Parameters { get; set; } = new Dictionary<string, object>();
|
||||
|
||||
private PSDataCollection<PSObject> _results = new PSDataCollection<PSObject>();
|
||||
public PSDataCollection<PSObject> Results { get => _results; private set => SetProperty(ref _results, value, nameof(Results)); }
|
||||
|
||||
public ObservableCollection<string> Console { get; set; } = new ObservableCollection<string>();
|
||||
|
||||
public ScriptBlock Script { get => ScriptFragments.FirstOrDefault(); }
|
||||
|
||||
public NetworkCredential Credential { get; set; }
|
||||
|
||||
public List<ScriptBlock> ScriptFragments { get; set; } = new List<ScriptBlock>();
|
||||
|
||||
#endregion // properties
|
||||
|
||||
#region methods
|
||||
|
||||
private bool CheckScript() {
|
||||
try
|
||||
{
|
||||
string _source;
|
||||
foreach (var s in ScriptFragments)
|
||||
{
|
||||
_source = s.ToString();
|
||||
ScriptBlock.Create(_source);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public ParamBlockAst GetParamBlock() {
|
||||
CheckScript();
|
||||
dynamic ast = Script?.Ast;
|
||||
return ast?.ParamBlock;
|
||||
}
|
||||
|
||||
public ScriptRequirements GetScriptRequirements() {
|
||||
CheckScript();
|
||||
dynamic ast = Script?.Ast;
|
||||
return ast?.ScriptRequirements;
|
||||
}
|
||||
|
||||
public void SetProxyVariable(string VariableName, object Value) {
|
||||
proxyVariables.Add((VariableName, Value));
|
||||
}
|
||||
|
||||
public async void Run(object Input = null) {
|
||||
|
||||
try
|
||||
{
|
||||
var _result = new PSDataCollection<PSObject>();
|
||||
|
||||
if (Input != null)_result.Add((PSObject)Input);
|
||||
|
||||
|
||||
var source = Script.ToString().Trim();
|
||||
currentPowerShell.AddScript(source, true);
|
||||
|
||||
if (this.Parameters != null)
|
||||
{
|
||||
foreach (var p in Parameters)
|
||||
{
|
||||
currentPowerShell.AddParameter(p.Key, p.Value);
|
||||
}
|
||||
}
|
||||
|
||||
// Merge results into a single collection of objects to be parsed later.
|
||||
currentPowerShell.Commands.Commands[0].MergeMyResults(PipelineResultTypes.All, PipelineResultTypes.Output);
|
||||
|
||||
// If there is any input pass it in, otherwise just invoke
|
||||
// the pipeline.
|
||||
if (Input != null)
|
||||
{
|
||||
_result = await RunAsync(Input); //new PSDataCollection<PSObject>(currentPowerShell.Invoke(new object[] { Input }));
|
||||
}
|
||||
else
|
||||
{
|
||||
try
|
||||
{
|
||||
_result = await RunAsync();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Results?.Add(new PSObject(e.GetAllMessages()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
foreach (var r in _result)
|
||||
{
|
||||
Results?.Add(r);
|
||||
}
|
||||
OnPropertyChanged(nameof(Results));
|
||||
|
||||
|
||||
foreach (var s in ScriptFragments.Skip(1))
|
||||
{
|
||||
currentPowerShell.AddScript(s.ToString());
|
||||
_result = await RunAsync();
|
||||
foreach (var r in _result)
|
||||
{
|
||||
Results?.Add(r);
|
||||
}
|
||||
OnPropertyChanged(nameof(Results));
|
||||
}
|
||||
|
||||
var exit = 0;
|
||||
try { exit = Convert.ToInt32(currentPowerShell.Runspace.SessionStateProxy.GetVariable("LastExitCode")); }
|
||||
catch { /* Don't really care about this */ }
|
||||
ExitCode = exit;
|
||||
|
||||
OnPropertyChanged(nameof(Results));
|
||||
}
|
||||
finally {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#if false
|
||||
public void RunAs(AdminUser user, object Input = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var source = Script.ToString().Trim();
|
||||
currentPowerShell.AddScript(source, true);
|
||||
|
||||
if (this.Parameters != null)
|
||||
{
|
||||
foreach (var p in Parameters)
|
||||
{
|
||||
currentPowerShell.AddParameter(p.Key, p.Value);
|
||||
}
|
||||
}
|
||||
|
||||
// Merge results into a single collection of objects to be parsed later.
|
||||
currentPowerShell.Commands.Commands[0].MergeMyResults(PipelineResultTypes.All, PipelineResultTypes.Output);
|
||||
|
||||
// If there is any input pass it in, otherwise just invoke
|
||||
// the pipeline.
|
||||
using (Runspace runspace = RunspaceFactory.CreateRunspace())
|
||||
{
|
||||
runspace.Open();
|
||||
|
||||
currentPowerShell.Runspace = runspace;
|
||||
|
||||
foreach (var proxyVar in proxyVariables)
|
||||
{
|
||||
currentPowerShell?.Runspace.SessionStateProxy.SetVariable(proxyVar.Item1, proxyVar.Item2);
|
||||
}
|
||||
|
||||
using (WindowsIdentity newId = new WindowsIdentity(user.IdentityHandle.DangerousGetHandle()))
|
||||
{
|
||||
using (WindowsImpersonationContext impersonatedUser = newId.Impersonate())
|
||||
{
|
||||
Debug.WriteLine($"Env user: {Environment.GetEnvironmentVariable("%username%")}");
|
||||
if (Input != null)
|
||||
{
|
||||
Results = new PSDataCollection<PSObject>(currentPowerShell.Invoke(new object[] { Input }));
|
||||
}
|
||||
else
|
||||
{
|
||||
try
|
||||
{
|
||||
Results = new PSDataCollection<PSObject>(currentPowerShell.Invoke());
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Results?.Add(new PSObject(e.GetAllMessages()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var exit = 0;
|
||||
try { exit = Convert.ToInt32(currentPowerShell.Runspace.SessionStateProxy.GetVariable("LastExitCode")); }
|
||||
catch { /* Don't really care about this */ }
|
||||
ExitCode = exit;
|
||||
|
||||
runspace.Close();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
/* Dont use any of this!!!! It doesn't work yet!!!
|
||||
private BlockingCollection<InformationalRecord> PSOutput = new BlockingCollection<InformationalRecord>();
|
||||
private Task ForwardMessages;
|
||||
*/
|
||||
|
||||
|
||||
public async Task<PSDataCollection<PSObject>> RunAsync(object Input = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var source = Script.ToString().Trim();
|
||||
currentPowerShell.AddScript(source, true);
|
||||
|
||||
if (this.Parameters != null)
|
||||
{
|
||||
foreach (var p in Parameters)
|
||||
{
|
||||
currentPowerShell.AddParameter(p.Key, p.Value);
|
||||
}
|
||||
}
|
||||
|
||||
// Merge results into a single collection of objects to be parsed later.
|
||||
currentPowerShell.Commands.Commands[0].MergeMyResults(PipelineResultTypes.All, PipelineResultTypes.Output);
|
||||
|
||||
return await Task.Factory.FromAsync(currentPowerShell.BeginInvoke<object>(Input), result => currentPowerShell.EndInvoke(result));
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<PSDataCollection<PSObject>> RunAsync(String Source, Dictionary<string, object> Parameters=null, object Input = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
currentPowerShell.AddScript(Source, true);
|
||||
|
||||
if (this.Parameters != null)
|
||||
{
|
||||
foreach (var p in Parameters)
|
||||
{
|
||||
currentPowerShell.AddParameter(p.Key, p.Value);
|
||||
}
|
||||
}
|
||||
|
||||
// Merge results into a single collection of objects to be parsed later.
|
||||
currentPowerShell.Commands.Commands[0].MergeMyResults(PipelineResultTypes.All, PipelineResultTypes.Output);
|
||||
|
||||
return await Task.Factory.FromAsync(currentPowerShell.BeginInvoke<object>(Input), result => currentPowerShell.EndInvoke(result));
|
||||
}
|
||||
finally
|
||||
{
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#endregion // methods
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
<package id="Microsoft.PowerShell.5.ReferenceAssemblies" version="1.1.0" targetFramework="net461" />
|
||||
<package id="Refractored.MvvmHelpers" version="1.6.2" targetFramework="net461" />
|
||||
<package id="System.Numerics.Vectors" version="4.5.0" targetFramework="net461" />
|
||||
<package id="System.ValueTuple" version="4.5.0" targetFramework="net461" />
|
||||
</packages>
|
Loading…
Reference in New Issue