PowerShelling

Windows PowerShell 

VarsWrite-Host "1st parm is: " $args[0];

$tmpLocalVar1 = "someTempLocalVar";
Write-Host "local val is: " tmpLocalVar1;

$ddlFile = $args[0];
Write-Host "Loading DLL: " dllFile;


Pass parms/args into powershell

Write-Host "Loading DLL: " $args[0];


powershell .\parm_args.ps1 bla
Loading DLL:  bla

Env Vars
  [Environment]::SetEnvironmentVariable("MyVar", "My Val", "User")
[Environment]::GetEnvironmentVariable("MyVar","User")

Pass commands into powershell via 1 dos line


powershell -Command [Reflection.Assembly]::LoadFile($(get-location).Path +\"\\SharedLib.dll\"); [SharedLib.Help]::help();


Echo text to user 

Write-Host "Loading DLL: " 
[Reflection.Assembly]::LoadFile("C:\app\DLLs\SharedLib.dll")

Write-Host "DLL version: " 
[System.Diagnostics.FileVersionInfo]::GetVersionInfo("C:\app\DLLs\SharedLib.dll").FileVersion

Write-Host "Listing static method definitions: " 
[SharedLib.UtilsDataBase]|Get-Member -static | Select-Object Definition

Write-Host "Calling static method Test: " 
[SharedLib.UtilsDataBase]::Test();

Write-Host "ORACLE_HOME env var: " 
Get-ChildItem Env:ORACLE_HOME



ISE = Integrated Scripting Environment 


View version


PS C:\Windows\Microsoft.NET\Framework\v4.0.30319> $PSVersionTable.PSVersion

Major  Minor  Build  Revision
-----  -----  -----  --------
2      0      -1     -1

Environment Variables on Win7
C:\Users\MDockery>set ps

PSModulePath=C:\windows\system32\WindowsPowerShell\v1.0\Modules\


DLL support for .NET 4.0

Support both .NET 2.0 and .NET 4 DLL's/assemblies:

notepad/Edit:
$pshome\powershell.exe.config 
and 
$pshome\powershell_ise.exe.config 

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <!-- http://msdn.microsoft.com/en-us/library/w4atty68.aspx -->
  <startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0" />
    <supportedRuntime version="v2.0.50727" />
  </startup>
</configuration>

$pshome location:
32-bit machines: C:\Windows\System32\WindowsPowershell\v1.0
64-bit machines also have the 32bit version:
32-bit: C:\Windows\SysWOW64\WindowsPowershell\v1.0


Sample/simple c# DLL class
namespace FunLib{ 
  public class MyClass{ 
    public MyClass(){}
    public static int StaticSum(int a, int b){ 
      return a + b; 
    }
    public int InstanceProduct(int a, int b){ 
      return a * b; 
    } 
  } 
}
Call a DLL's static method
   [Reflection.Assembly]::LoadFile(“C:\app\DLLs\SharedLib.dll”)
   [SharedLib.UtilsGui]::ShowHelpForm();
or 

   [Reflection.Assembly]::LoadFile(“C:\app\DLLs\SharedLib.dll”)

   [SharedLib.UtilsDataBase]::Test();

Call a DLL's instance method
   $myInstance = new-object FunLib.MyClass
   $myInstance.InstanceProduct(3, 3)



powershell - list static methods and variables

[Reflection.Assembly]::LoadFile(“C:\app\DLLs\SharedLib.dll”)

[SharedLib.UtilsDataBase]|Get-Member -static

TypeName: SharedLib.UtilsDatabase
Name                              MemberType Definition
----                              ---------- ----------
CloseOracleStaticConnection       Method     static void CloseOracleStaticConnection()
Equals                            Method     static bool Equals(System.Object objA, System.Object objB)
GetCleanSqlWithLineBreaks         Method     static string GetCleanSqlWithLineBreaks(string sql)
GetColNamesAndTypes               Method     static System.Collections.Generic.Dictionary[string,string] GetColNamesAndTypes(string sqlString, Oracle.Manag
GetColType                        Method     static string GetColType(Oracle.ManagedDataAccess.Client.OracleDataReader oraReader, int colIdx)
...

show version
[System.Diagnostics.FileVersionInfo]::GetVersionInfo("C:\app\DLLs\SharedLib.dll").FileVersion

call a static method
[SharedLib.UtilsDataBase]::Test();




A better static method call example
C:\app\DLLs>powershell
PS C:\app\DLLs> [Reflection.Assembly]::LoadFile($(get-location).Path +"\SharedLib.dll"); [SharedLib.UtilsGui]::ShowHelpForm();

GAC    Version        Location
---    -------        --------
False  v4.0.30319     C:\app\DLLs\SharedLib.dll


PS C:\app\DLLs>


Another example of calling static DLL functions:

C:\WINDOWS\system32\WindowsPowerShell\v1.0>powershell.exe

Windows PowerShell

PS> [Reflection.Assembly]::LoadFile("C:\app\DLLs\SharedLib.dll")
GAC    Version        Location
---    -------        --------
False  v4.0.30319     C:\app\DLLs\SharedLib.dll

PS> [SharedLib.UtilsClass]::getVersion()
Assembly Version:3.2.2.0
descriptionTitle:SharedLib classes: UtilsFTP, UtilsWeb and UtilsDb containing useful functions.
prodNameDependancy:Depends on Oracle.ManagedDataAccess.dll, WinSCP.dll, WinSCP.exe
Company:MyCo
3.2.2.0 SharedLib classes: UtilsFTP,  UtilsWeb and UtilsDb containing useful functions.

Compile with powershell and .net 

PS H:\> csc
  The term 'csc' is not recognized as the name of a cmdlet, function, script file, or operable program. 


PS H:\> cd C:\Windows\Microsoft.NET\Framework\v4.0.30319

PS C:\Windows\Microsoft.NET\Framework\v4.0.30319> ./csc
  Microsoft (R) Visual C# Compiler version 4.0.30319.18408 for Microsoft (R) .NET Framework 4.5
  ...



Environment variables

$ScriptDirectory = (gi $PSCommandPath).DirectoryName
Join-Path $ScriptDirectory "MyPSAssembly.dll"
temp dir
 $LocalDllPath = Join-Path $env:temp $dllname 

Multiple commands on 1 line

Use a semicolon to chain commands in powershell:
ipconfig /release; ipconfig /renew

Download the latest if you get this error


Exception calling "LoadFile" with "1" argument(s): "This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.
 0x8013101B)"
At line:1 char:32
+ [Reflection.Assembly]::LoadFile <<<< ("C:\app\DLLs\SharedLib.dll")
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

PS C:\app\DLLs>


PS C:\app\DLLs> $PSVersionTable

Name                           Value
----                           -----
CLRVersion                     2.0.50727.5485
BuildVersion                   6.1.7601.17514
PSVersion                      2.0
WSManStackVersion              2.0
PSCompatibleVersions           {1.0, 2.0}
SerializationVersion           1.1.0.1
PSRemotingProtocolVersion      2.1


(Get-ItemProperty -Path 'HKLM:\Software\Microsoft\NET Framework Setup\NDP\v4\Full' -ErrorAction SilentlyContinue).Version -like '4.5*'


https://www.microsoft.com/en-us/download/details.aspx?id=40855

Windows6.1-KB2819745-x64-MultiPkg.msu

Windows Management Framework 4.0
  includes updates to
Windows PowerShell,
Windows PowerShell ISE,
Windows PowerShell Web Services (Management OData IIS Extension),
Windows Remote Management (WinRM),
Windows Management Instrumentation (WMI), the
Server Manager WMI provider, and a new feature for 4.0,
Windows PowerShell Desired State Configuration (DSC).


To prepare for installation of Windows Management Framework 4.0:
Download the correct package for your os/architecture: Win7 SP1 x64: Windows6.1-KB2819745-x64-MultiPkg.msu
Close all Windows PowerShell windows.
Uninstall any other copies of Windows Management Framework 4.0, including any prerelease copies or copies in other languages.
Double-click the MSU to run it.


To uninstall Windows Management Framework 4.0:
In Control Panel\Programs\Programs and Features\Uninstall a program, locate and then uninstall the following installed Windows Update:
KB2819745 - for Windows 7 SP1 and Windows Server 2008 R2 SP1


Gui popups

$wshell = New-Object -ComObject Wscript.Shell;
$yes = 6;
$no = 7;
$newLine = "`n";
$verboseUserResponse = $wshell.Popup("Want to see Detailed/Verbose info "+$newLine+" for the following DLL file? $pathAndDll",0,"Verbose or Brief/Summary",0x3)

Write-Host "    user selected = ${val}";

if($verboseUserResponse -eq $yes){
  Write-Host " Showing verbose information ";
}


Get DLL info


Param([String]$pathAndDll)
Write-Host "******************************************************";
Write-Host "  Author....: Michael Dockery";
Write-Host "  Created...: Dec 2016";
Write-Host "  Purpose...: Interrogate a DLL by showing static methods and properties"
Write-Host "  Note: this will AUTO-run any function called Test or getVersion"
Write-Host "******************************************************";
if (!$pathAndDll){
     #$pathAndDll="C:\app\DLLs\SharedLib.dll";
$pathAndDll="C:\app\DLLs\IRD_To_MS2_Project.exe";

     Write-Host "DLL pathAndDll parm is null, so using default of " $pathAndDll
}
<#            To see any errors, run from cmdline, then type: "
              $x = $Error[0] "
              $x.Exception.InnerException.LoaderExceptions "
#>
$wshell = New-Object -ComObject Wscript.Shell;
$yes = 6;
$no = 7;
$newLine = "`n";
$verboseUserResponse = $wshell.Popup("Want to see Detailed/Verbose info "+$newLine+" for the following DLL file? $pathAndDll",0,"Verbose or Brief/Summary",0x3)

Write-Host "    user selected = ${val}";

if($verboseUserResponse -eq $yes){
  Write-Host " Showing verbose information ";
}

Write-Host "  Loading:" $pathAndDll
$dll = [Reflection.Assembly]::LoadFrom($pathAndDll);

Write-Host "ORACLE_HOME env var: "
Get-ChildItem Env:ORACLE_HOME

Write-Host " "
Write-Host "-----------------------------------"
$dllVer = [System.Diagnostics.FileVersionInfo]::GetVersionInfo($pathAndDll).FileVersion
Write-Host "  DLL version: " $dllVer

Write-Host " "
Write-Host "-----------------------------------"
Write-Host "  Showing public static TYPES (properties and methods):";
$typesArray = $dll.GetTypes()
foreach ($typ in $typesArray) {
#if($typ.IsPublic -eq $True -and $typ.FullName -Match "DataB"){
if($typ.IsPublic -eq $True){
   Write-Host "    --------------------------";
Write-Host "    Type = ${typ}";
if($verboseUserResponse -eq $yes){
#$members = $typ|Get-Member -static  | sort MemberType -Descending
$members = $typ|Get-Member -static  | sort MemberType, Name
foreach ($member in $members) {
$mName = $member.Name;
$mType = $member.MemberType;
Write-Host "        $mType $mName";
if($mType -eq "Method" -and ($mName -eq "Test" -or $mName -Match "getVersion")){
Write-Host "        -----*-----*-----*-----*-----*-----*-----*-----";
Write-Host "        ${typ}.$mName method found, running it now...";
$typ::$mName();
Write-Host "        -----*-----*-----*-----*-----*-----*-----*-----";
}
}
}
}
}

Write-Host "-------------------------------------------------------------------"
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
$varr = $wshell.Popup("The DLL information was shown on the dos screen "+$newLine+" if you saw any red errors, ensure any dll dependancies are in the same dir",0,"Done",0x1);



Comments

Popular Posts