I have a code to import a dll to my scripts. But i'm copying this part of code in every script where I'm using this dll. I think this is not a good practice. What would be a good practice here to avoid code replication.
Example of what i'm doing:
function Backup-Database
{
$pathSMO = "C:\Program Files\Microsoft SQL Server\110\SDK\Assemblies\Microsoft.SqlServer.Smo.dll"
$pathSMOEx = "C:\Program Files\Microsoft SQL Server\110\SDK\Assemblies\Microsoft.SqlServer.SmoExtended.dll"
#imports
Add-Type -path $pathSMO
Add-Type -path $pathSMOEx
#other stuff...
}
function Restore-Database
{
$pathSMO = "C:\Program Files\Microsoft SQL Server\110\SDK\Assemblies\Microsoft.SqlServer.Smo.dll"
$pathSMOEx = "C:\Program Files\Microsoft SQL Server\110\SDK\Assemblies\Microsoft.SqlServer.SmoExtended.dll"
#imports
Add-Type -path $pathSMO
Add-Type -path $pathSMOEx
#other stuff...
}
Forgive me if i'm off base but you should just be able to move the type declaration above the functions and still have it accessible within the functions. Bastardizing example 1 from the TechNet for Add-Type
$source = @"
public class BasicTest
{
public static int Add(int a, int b)
{
return (a + b);
}
public int Multiply(int a, int b)
{
return (a * b);
}
}
"@
Add-Type -TypeDefinition $source
function test1{
[BasicTest]::Add(4, 3)
}
Function test2{
$basicTestObject = New-Object BasicTest
$basicTestObject.Multiply(5, 2)
}
test1
test2
Output from code above
7
10
As you can see the definition is outside the functions. Hopefully using the quote in proper context if the -NameSpace
parameter is omitted then the type is generated in the global namespace.