Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent to C#'s "using" keyword in powershell?

When I use another object in the .net-Framework in C# I can save a lot of typing by using the using directive.

using FooCompany.Bar.Qux.Assembly.With.Ridiculous.Long.Namespace.I.Really.Mean.It;  ...     var blurb = new Thingamabob();  ... 

So is there a way in Powershell to do something similiar? I'm accessing a lot of .net objects and am not happy of having to type

 $blurb = new-object FooCompany.Bar.Qux.Assembly.With.Ridiculous.Long.Namespace.I.Really.Mean.It.Thingamabob; 

all the time.

like image 243
froh42 Avatar asked Jun 26 '09 12:06

froh42


People also ask

What is equivalent in C?

C *= A is equivalent to C = C * A. /= Divide AND assignment operator. It divides the left operand with the right operand and assigns the result to the left operand. C /= A is equivalent to C = C / A.

What does &= mean in C?

It means to perform a bitwise operation with the values on the left and right-hand side, and then assign the result to the variable on the left, so a bit of a short form.

What is the C equivalent of CIN?

Standard Input Stream (cin) in C++ It corresponds to the C stream stdin. The standard input stream is a source of characters determined by the environment.

How do you write not equal to in C?

The not-equal-to operator ( != ) returns true if the operands don't have the same value; otherwise, it returns false .


2 Answers

There's really nothing at the namespace level like that. I often assign commonly used types to variables and then instantiate them:

$thingtype = [FooCompany.Bar.Qux.Assembly.With.Ridiculous.Long.Namespace.I.Really.Mean.It.Thingamabob]; $blurb = New-Object $thingtype.FullName 

Probably not worth it if the type won't be used repeatedly, but I believe it's the best you can do.

like image 148
dahlbyk Avatar answered Oct 06 '22 22:10

dahlbyk


PowerShell 5.0 (included in WMF5 or Windows 10 and up), adds the using namespace construct to the language. You can use it in your script like so:

#Require -Version 5.0 using namespace FooCompany.Bar.Qux.Assembly.With.Ridiculous.Long.Namespace.I.Really.Mean.It $blurb = [Thingamabob]::new() 

(The #Require statement on the first line is not necessary to use using namespace, but it will prevent the script from running in PS 4.0 and below where using namespace is a syntax error.)

like image 39
Brant Bobby Avatar answered Oct 06 '22 23:10

Brant Bobby