문제

내가 사용하는 경우 다른 개체.net 프레임워크에서는 C#나는 많이 저장할 수 있습의 입력을 사용하여 사용하는 지시어.

using FooCompany.Bar.Qux.Assembly.With.Ridiculous.Long.Namespace.I.Really.Mean.It;

...


  var blurb = new Thingamabob();

...

그래서 거기에서 방법을 Powershell 무언가를 하는 유사한?나에 액세스합니다.net 개체고 행복하지 못하는 데 유형

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

니다.

도움이 되었습니까?

해결책

PowerShell5.0(에 포함되어 있 WMF5 또는 윈도우 10)에 추가합니다 using namespace 을 구성하는 언어입니다.에서 사용할 수 있고 스크립트는 다음과 같이

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

(의 #Require 문의 첫 번째 라인을 사용할 필요가 없 using namespace, 지만,그것은 것을 방지하는 스크립트에서 실행되는 PS4.0 고 아래는 using namespace 구문 오류가 있습니다.)

다른 팁

정말 아무것도 없 네임스페이스 수준에서 다음과 같다.저는 종종 할당 일반적으로 사용되는 유형을 변수와 초기화들:

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

아마도 그것을 가치가 없는 경우에는 사용되지 않습 반복적으로,그러나 그것을 믿고 최선을 할 수 있습니다.

이 블로그 포스팅에서 몇 년 전: http://blogs.msdn.com/richardb/archive/2007/02/21/add-types-ps1-poor-man-s-using-for-powershell.aspx

add-types.ps1, 에서 발췌하는 기사:

param(
    [string] $assemblyName = $(throw 'assemblyName is required'),
    [object] $object
)

process {
    if ($_) {
        $object = $_
    }

    if (! $object) {
        throw 'must pass an -object parameter or pipe one in'
    }

    # load the required dll
    $assembly = [System.Reflection.Assembly]::LoadWithPartialName($assemblyName)

    # add each type as a member property
    $assembly.GetTypes() | 
    where {$_.ispublic -and !$_.IsSubclassOf( [Exception] ) -and $_.name -notmatch "event"} | 
    foreach { 
        # avoid error messages in case it already exists
        if (! ($object | get-member $_.name)) {
            add-member noteproperty $_.name $_ -inputobject $object
        }
    }
}

고,그것을 사용:

RICBERG470> $tfs | add-types "Microsoft.TeamFoundation.VersionControl.Client"
RICBERG470> $itemSpec = new-object $tfs.itemspec("$/foo", $tfs.RecursionType::none)

기본적으로 어떻게 하는 것은 크롤링 어셈블리를 위해 특수 유형,다음 쓰기"자"는 추가를 사용하여-회원 추가하(에서는 구조화된 방법으로)객체해요.

또한 이 후속 post: http://richardberg.net/blog/?p=38

이것은 그냥 농담이 농담...

$fullnames = New-Object ( [System.Collections.Generic.List``1].MakeGenericType( [String]) );

function using ( $name ) { 
foreach ( $type in [Reflection.Assembly]::LoadWithPartialName($name).GetTypes() )
    {
        $fullnames.Add($type.fullname);
    }
}

function new ( $name ) {
    $fullname = $fullnames -like "*.$name";
    return , (New-Object $fullname[0]);
}

using System.Windows.Forms
using FooCompany.Bar.Qux.Assembly.With.Ridiculous.Long.Namespace.I.Really.Mean.It
$a = new button
$b = new Thingamabob

여기에 몇 가지 작동하는 코드에서 PowerShell2.0 를 추가하는 형식 별칭을 사용합니다.그러나 문제는 그 범위가 지정되어 있습니다.몇 가지 추가 작업을 수 있는"유엔 가져오는"네임스페이스,그러나 이것은 당신을 얻을 좋은 시작합니다.

##############################################################################
#.SYNOPSIS
# Add a type accelerator to the current session.
#
#.DESCRIPTION
# The Add-TypeAccelerator function allows you to add a simple type accelerator
# (like [regex]) for a longer type (like [System.Text.RegularExpressions.Regex]).
#
#.PARAMETER Name
# The short form accelerator should be just the name you want to use (without
# square brackets).
#
#.PARAMETER Type
# The type you want the accelerator to accelerate.
#
#.PARAMETER Force
# Overwrites any existing type alias.
#
#.EXAMPLE
# Add-TypeAccelerator List "System.Collections.Generic.List``1"
# $MyList = New-Object List[String]
##############################################################################
function Add-TypeAccelerator {

    [CmdletBinding()]
    param(

        [Parameter(Position=1,Mandatory=$true,ValueFromPipelineByPropertyName=$true)]
        [String[]]$Name,

        [Parameter(Position=2,Mandatory=$true,ValueFromPipeline=$true)]
        [Type]$Type,

        [Parameter()]
        [Switch]$Force

    )

    process {

        $TypeAccelerators = [Type]::GetType('System.Management.Automation.TypeAccelerators')

        foreach ($a in $Name) {
            if ( $TypeAccelerators::Get.ContainsKey($a) ) {
                if ( $Force ) {
                    $TypeAccelerators::Remove($a) | Out-Null
                    $TypeAccelerators::Add($a,$Type)
                }
                elseif ( $Type -ne $TypeAccelerators::Get[$a] ) {
                    Write-Error "$a is already mapped to $($TypeAccelerators::Get[$a])"
                }
            }
            else {
                $TypeAccelerators::Add($a, $Type)
            }
        }

    }

}

만 필요한 경우에는 인스턴스를 만들의 입력,저장할 수 있습니다 이름의 네임스페이스에서 문자열:

$st = "System.Text"
$sb = New-Object "$st.StringBuilder"

그만큼 강력 using 지시어에서 C#,하지만 적어도 그것은 사용하기 매우 쉽습니다.

셔서 감사합니다 모두에 대한 귀하의 입력이 있습니다.되 리차드 베르그의 기여에 대한 답변으로,때문에 그것을과 가장 유사한 내가 무엇을 찾고 있습니다.

귀하의 모든 답변을 가져 나이 트랙에서는 가장 유망한 것 같:에 그의 블로그에 포스트 Keith Dahlby 제안을 얻을 형 commandlet 용할 수 있게 해주는 consutruction 의 유형에 대한 일반적인 방법입니다.

나는 생각은 없는 이유에 대해 exetending 이하도 검색을 통해 미리 정의한 경로의 어셈블리에 대한 형식이 있습니다.

면책 조항:지 않았는 아직-...

여기에는 방법이 하나를 사용할 수 있다:

$path = (System.Collections.Generic, FooCompany.Bar.Qux.Assembly.With.Ridiculous.Long.Namespace.I.Really.Mean.It)

$type = get-type -Path $path List Thingamabob
$obj = new-object $type
$obj.GetType()

이 결과에 좋은 일반 목록 Thingamabob.물론 내가 랩까지 모든 산세 경로 정의에서 또 다른 유틸리티 기능입니다.Extended 얻을 형을 포함할 것입을 해결 단계 모든 지정된 형식으로 전년도 합니다.

#Requires -Version 5
using namespace System.Management.Automation.Host
#using module

내가 이것을 깨닫는 이 게스트,하지만 나는 동일한 것을 찾는 이름: http://weblogs.asp.net/adweigert/powershell-adding-the-using-statement

편집:내가 지정해야 하는 것으로 사용할 수 있는 익숙한 구문을...

using ($x = $y) { ... }
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top