“Invalid directory on URL” 在尝试使用 Powershell 中使用 New-PSDrive 创建的路径时。

huangapple go评论79阅读模式
英文:

"Invalid directory on URL" while trying to use path created using New-PSDrive in Powershell

问题

我已经编写了一个获取身份验证令牌的函数。我使用了 New-PSDrive,因为抛出了 PathTooLongException 异常。在测试路径是否存在时,Write-Host $adal, (Test-Path $adal) 返回 True。但在 LoadFrom() 中抛出异常。有人可以帮助我消除错误吗?

代码:

function GetAuthToken {
    try{
        Write-Host "GetAuthToken-Start"
        If (!(Test-Path CustomDrive:)){
            $adalPath = Get-Module -Name "AzureRM.Profile" -ListAvailable -All | Select -First 1 | Select -ExpandProperty ModuleBase
            New-PSDrive -Name "CustomDrive" -PSProvider filesystem -Root $adalPath
            Write-Host "Created CustomDrive."
        }
        
        $adal = "CustomDrive:\Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
        $adalforms = "CustomDrive:\Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms.dll"
            
        Write-Host $adal, (Test-Path $adal) #Test-Path 返回 True
        Write-Host $adalforms, (Test-Path $adalforms)
        
        Write-Host "Loading required DLLs..."
        [System.Reflection.Assembly]::LoadFrom($adal) | Out-Null #此行引发异常
        [System.Reflection.Assembly]::LoadFrom($adalforms) | Out-Null
        Write-Host "Loaded required DLLs successfully."

        Write-Host "Trying to acquire token..."
        $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authorityUri
        $authResult = $authContext.AcquireToken($resourceUri, $clientId, $redirectUri, "Always") 
        Write-Host "Acquired token successfully."

        Write-Host $authResult
        Write-Host "GetAuthToken-End"
        return $authResult
    }
    catch{
        Write-Error -Message $_.Exception
        throw $_.Exception
    }
    finally{
        Remove-PSDrive -Name "CustomDrive"
        Write-Host "Removed CustomDrive."
    }
}

异常:

GetAuthToken : System.Management.Automation.MethodInvocationException: Exception calling "LoadFrom" with "1" argument(s): "Invalid directory on 
URL." ---> System.ArgumentException: Invalid directory on URL.
   at System.Security.Util.DirectoryString.CreateSeparatedString(String directory)
   at System.Security.Util.URLString.ParseFileURL(String url)
   at System.Security.Util.URLString.GetFileName()
   at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly 
reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean 
suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadFrom(String assemblyFile, Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm 
hashAlgorithm, Boolean forIntrospection, Boolean suppressSecurityChecks, StackCrawlMark& stackMark)
   at System.Reflection.Assembly.LoadFrom(String assemblyFile)
   at CallSite.Target(Closure , CallSite , Type , Object )
   --- End of inner exception stack trace ---
   at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
   at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
英文:

I have written a function to get authentication token. I have used New-PSDrive because PathTooLongException was thrown. Write-Host $adal, (Test-Path $adal) returns True while testing if path exists. But throws exception in LoadFrom(). Could someone help me get rid of the error?

Code:

function GetAuthToken {
    try{
        Write-Host "GetAuthToken-Start"
        If (!(Test-Path CustomDrive:)){
            $adalPath = Get-Module -Name "AzureRM.Profile" -ListAvailable -All | Select -First 1 | Select -ExpandProperty ModuleBase
            New-PSDrive -Name "CustomDrive" -PSProvider filesystem -Root $adalPath
            Write-Host "Created CustomDrive."
        }
        
        $adal = "CustomDrive:\Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
        $adalforms = "CustomDrive:\Microsoft.IdentityModel.Clients.ActiveDirectory.WindowsForms.dll"
            
        Write-Host $adal, (Test-Path $adal) #Test-Path returns True
        Write-Host $adalforms, (Test-Path $adalforms)
        
        Write-Host "Loading required DLLs..."
        [System.Reflection.Assembly]::LoadFrom($adal) | Out-Null #This line throws exception
        [System.Reflection.Assembly]::LoadFrom($adalforms) | Out-Null
        Write-Host "Loaded required DLLs successfully."

        Write-Host "Trying to acquire token..."
        $authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authorityUri
        $authResult = $authContext.AcquireToken($resourceUri, $clientId, $redirectUri, "Always") 
        Write-Host "Acquired token successfully."

        Write-Host $authResult
        Write-Host "GetAuthToken-End"
        return $authResult
    }
    catch{
        Write-Error -Message $_.Exception
        throw $_.Exception
    }
    finally{
        Remove-PSDrive -Name "CustomDrive"
        Write-Host "Removed CustomDrive."
    }
}

Exception:

GetAuthToken : System.Management.Automation.MethodInvocationException: Exception calling "LoadFrom" with "1" argument(s): "Invalid directory on 
URL." ---> System.ArgumentException: Invalid directory on URL.
   at System.Security.Util.DirectoryString.CreateSeparatedString(String directory)
   at System.Security.Util.URLString.ParseFileURL(String url)
   at System.Security.Util.URLString.GetFileName()
   at System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly 
reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean 
suppressSecurityChecks)
   at System.Reflection.RuntimeAssembly.InternalLoadFrom(String assemblyFile, Evidence securityEvidence, Byte[] hashValue, AssemblyHashAlgorithm 
hashAlgorithm, Boolean forIntrospection, Boolean suppressSecurityChecks, StackCrawlMark& stackMark)
   at System.Reflection.Assembly.LoadFrom(String assemblyFile)
   at CallSite.Target(Closure , CallSite , Type , Object )
   --- End of inner exception stack trace ---
   at System.Management.Automation.ExceptionHandlingOps.CheckActionPreference(FunctionContext funcContext, Exception exception)
   at System.Management.Automation.Interpreter.ActionCallInstruction`2.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)

答案1

得分: 0

感谢 @mclayton 告知了根本原因。

在 PowerShell 中,使用 Add-Type 而不是 LoadForm() 来加载程序集。

Add-Type -Path $adal
英文:

Thanks to @mclayton for letting know the root cause.

Used Add-Type instead of LoadForm() to load the assembly in powershell.

Add-Type -Path $adal

huangapple
  • 本文由 发表于 2020年1月4日 01:53:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/59583133.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定