I have some Powershell code that takes the Apps running on an IIS server and finds the versions of .NET they are running.
$Apps = Get-WebApplication
foreach($App in $Apps) {
$binLocation = "$($App.physicalPath)\bin"
# get all dlls in bin folder
$dllFolder = Get-Item -Path $binLocation
$dlls = $dllFolder.GetFiles("*.dll")
# analyze dll .net version
$set = New-Object System.Collections.Generic.HashSet[String]
$dlls | ForEach-Object {
$set.Add([Reflection.Assembly]::ReflectionOnlyLoadFrom("$binLocation\$($_.Name)").ImageRuntimeVersion) | Out-Null
}
# print all dll .NET version
$App
$set
}
However when I run this on my server I get 2 types of error;
Exception calling "ReflectionOnlyLoadFrom" with "1" argument(s): "API restriction: The
assembly 'file:///D:\inetpub\wwwroot\OABS_ECRM\bin\WebGrease.dll' has already loaded from a
different location. It cannot be loaded from a new location within the same appdomain."
At line:13 char:74
+ $set.Add([Reflection.Assembly]::ReflectionOnlyLoadFrom ("$binLocation\$($_.Name ...
+ ~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FileLoadException
and,
Exception calling "ReflectionOnlyLoadFrom" with "1" argument(s): "Could not load file or
assembly 'file:///D:\inetpub\wwwroot\Tablet\bin\epengine.dll' or one of its dependencies.
The module was expected to contain an assembly manifest."
At line:13 char:74
+ $set.Add([Reflection.Assembly]::ReflectionOnlyLoadFrom("$binLocation\$($_.Name ...
+ ~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : BadImageFormatException
I seem to get the .NET versions running on each app from the script but I was wondering what caused these errors and if they can be cleared. I need to solve this in powershell.
Loading multiple DLLs with the same identity into the same AppDomain will give you the first exception.
See my workaround at https://stackoverflow.com/a/62379741/920618.
Related
I my trying to connect to a client SFTP server from our Windows Server to pull the files. The connection works fine when trying from my Local machine both using WinSCP application and PowerShell script. But I have to add proxy setting while I am trying to connect from the server which is not the case in Local connection.
While in the server I am able to connect from WinSCP application by enabling proxy setting but fails when I am trying to connect using PowerShell script. I got the custom generated PowerShell script from WinSCP connection.
Below is the code snippet and corresponding error message.
$sessionOptions = New-Object WinSCP.SessionOptions -Property #{
Protocol = [WinSCP.Protocol]::SFTP
HostName = "<host name>"
PortNumber = 22
UserName = "<Username>"
SshPrivateKeyPath= "<private key>"
SshHostKeyFingerprint = "<SshHostKeyFingerprint>"
}
$sessionOptions.AddRawSettings("ProxyMethod", "3")
$sessionOptions.AddRawSettings("ProxyHost", "<proxyhost>")
$sessionOptions.AddRawSettings("ProxyPort", "3128")
$sessionOptions.AddRawSettings("ProxyLocalhost", "1")
getting below error message.
New-Object : The value supplied is not valid, or the property is read-only. Change the value, and then try again.
At line:3 char:19
+ $sessionOptions = New-Object WinSCP.SessionOptions -Property #{
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [New-Object], Exception
+ FullyQualifiedErrorId : SetValueException,Microsoft.PowerShell.Commands.NewObjectCommand
You cannot call a method on a null-valued expression.
At line:12 char:1
+ $sessionOptions.AddRawSettings("ProxyMethod", "3")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At line:13 char:1
+ $sessionOptions.AddRawSettings("ProxyHost", "<proxyhost>")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At line:14 char:1
+ $sessionOptions.AddRawSettings("ProxyPort", "3128")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At line:15 char:1
+ $sessionOptions.AddRawSettings("ProxyLocalhost", "1")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
The most probable explanation is that the value of SessionOptions.SshHostKeyFingerprint is invalid, no other property in your code is validated.
See also WinSCP .NET assembly in PowerShell - Creating SessionOptions - The value supplied is not valid, or the property is read-only
As your fingerprint format seems correct, but as it is a "modern" ssh-ed25519 key, I assume that you have an old version of WinSCP .NET assembly that does not accept this key. You have probably used newer version of WinSCP (the GUI) to obtain this key, but your version of .NET assembly does not accept it. Make sure you use the latest version of the assembly.
I am trying to change all the file creation date stamp to new time. I am using below code to do that. I am running this from a VM with an admin ID which as access to all the "FILE share servers".
Am my missing nay permissions to make changes to the files?
Note: File share servers are stored in different servers and I am using my own VM which is in same domain to access those file shares.I can access them through Network path from "RUN". Not sure while access denied error is thrown.
Function Set-FileTimeStamps { Param (
[Parameter(mandatory=$true)]
[string[]]$path,
[datetime]$date = (Get-Date) )
Get-ChildItem -Path $path |
ForEach-Object {
$_.CreationTime = $date
$_.LastAccessTime = $date
$_.LastWriteTime = $date } } Set-FileTimeStamps -path \\nwst01\test$\rgadagot "07/10/19 10:10"
error:
Exception setting "CreationTime": "Access to the path
'\nwst01\test$\user \Data' is denied." Exception setting
At line:10 char:6
+ $_.CreationTime = $date
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenSetting
Exception setting"LastAccessTime": "Access to the path '\nwst01\test$\user \Data' is
denied." At line:11 char:6
+ $_.LastAccessTime = $date
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenSetting
Exception setting "LastWriteTime": "Access to the path
'\nwst01\test$\user \Data' is denied." At line:12 char:6
+ $_.LastWriteTime = $date }
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenSetting
Welcome to stackoverflow.
Try to create a new file at that location (through the same script). If that fails, but you are able to create such a file otherwise, it may be a double-hop issue: Kerberos authentication prevents you from impersonating a 2nd time (even if you are logged in as a domain administrator). There is a workaround with CredSSP but maybe better look into the suggestion here: https://searchwindowsserver.techtarget.com/tutorial/How-to-avoid-the-double-hop-problem-with-PowerShell.
I am using Publish-Module and one of the modules had a bad psd1 file. PowerShell threw an exception as expected. The call to Publish-Module is inside a try block but the error handling code in the catch block never ran. It appears that this error is not being caught.
There is another error that happens in this same PowerShell code where the module I am publishing already exists in the repository. When that error occurs the code in the catch block runs and processes the exception. Is there something different about the first exception that would cause the catch block to be bypassed?
Code snippet:
try {
Publish-Module -Path .\$moduleName -Repository MyRepo -NuGetApiKey ghehdue
"Module $moduleName published."
}
catch {
if ($_.Exception.Message -ilike "*cannot be published as the current version*is already available in the repository*") {
"The latest version of module $moduleName already exists in the repository."
}
else {
$exitCode += 1
Write-Error $_
}
}
}
Error that is not caught
Microsoft.PowerShell.Core\Test-ModuleManifest : The module manifest 'J:\Builds\
Jenkins\PROJECT_2456764.0\Applications\ALM\PSModules\MyCompany.Build\MyCompany.B
uild.psd1' could not be processed because it is not a valid Windows PowerShell
restricted language file. Remove the elements that are not permitted by the
restricted language:
At J:\Builds\Jenkins\PROJECT_2456764.0\Applications\ALM\PSModules\MyCompany.Bui
ld\MyCompany.Build.psd1:13 char:9
+ GUID = 'ccaa548f-8194-4cfa-a659-260f6ddc556b'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unexpected token 'ccaa548f-8194-4cfa-a659-260f6ddc556b'
# Author of this module
Author = 'MyCompany'
# Company or vendor of this module
CompanyName = 'MyCompany' in expression or statement.
At J:\Builds\Jenkins\PROJECT_2456764.0\Applications\ALM\PSModules\MyCompany.Bui
ld\MyCompany.Build.psd1:13 char:9
+ GUID = 'ccaa548f-8194-4cfa-a659-260f6ddc556b'
+ ~
The hash literal was incomplete.
At J:\Builds\Jenkins\PROJECT_2456764.0\Applications\ALM\PSModules\MyCompany.Bui
ld\MyCompany.Build.psd1:19 char:25
+ CompanyName = 'MyCompany, Inc.'
+ ~
Missing argument in parameter list.
At J:\Builds\Jenkins\PROJECT_2456764.0\Applications\ALM\PSModules\MyCompany.Bui
ld\MyCompany.Build.psd1:118 char:1
+ }
+ ~
Unexpected token '}' in expression or statement.
At C:\Program Files
(x86)\WindowsPowerShell\Modules\PowerShellGet\1.0.0.1\PSModule.psm1:989 char:27
+ ... $module = Microsoft.PowerShell.Core\Test-ModuleManifest -Path $mani ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (J:\Builds\Jenki...Quip.Bui
ld.psd1:String) [Test-ModuleManifest], MissingMemberException
+ FullyQualifiedErrorId : Modules_InvalidManifest,Microsoft.PowerShell.Com
mands.TestModuleManifestCommand
Error that is caught
publish-module : The module 'DqCryptography' with version '1.0.2' cannot be published as the current version '1.0.2' is already available in the repository 'http://usas26:8624/nuget/PROJECTPowerShell/'.
At line:1 char:1
+ publish-module -Path DqCryptography -Repository PROJECTPowerShell - ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Publish-Module], InvalidOperationException
+ FullyQualifiedErrorId : ModuleVersionIsAlreadyAvailableInTheGallery,Publish-Module
Inside the try block add an error action to the Publish-Module
Publish-Module -Path .\$moduleName -Repository MyRepo -NuGetApiKey ghehdue -ErrorAction Stop
Whenever I open the package manager console in new VS 2017 session, it shows the below two error messages, and the for all intents and purposes operates normally. At least for vanilla commands like Install-Package.
Join-Path : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'ChildPath'. Specified method is not supported.
At C:\Dev\.NET\Projects\AcmeSoft\Code\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\tools\init.ps1:13 char:57
+ ... rPackageDirectory = Join-Path $packageDirectory $compilerPackage.Name
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Join-Path], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgument,Microsoft.PowerShell.Commands.JoinPathCommand
and
Join-Path : Cannot bind argument to parameter 'Path' because it is null.
At C:\Dev\.NET\Projects\AcmeSoft\Code\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.0\tools\init.ps1:14 char:44
+ ... erPackageToolsDirectory = Join-Path $compilerPackageDirectory 'tools'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Join-Path], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.JoinPathCommand
The offending line for the first is:
$compilerPackageDirectory = Join-Path $packageDirectory $compilerPackage.Name
with the error at $compilerPackage.Name (i.e. "char:57")
The offending line for the second is:
$compilerPackageToolsDirectory = Join-Path $compilerPackageDirectory 'tools'
with the error at $compilerPackageDirectory 'tools'.
Can anyone with more Nuget and or PowerShell skills than me explain why this is happening, and how I can fix it, please?
I am trying to write a PowerShell script to perform steps on multiple Word docs. I have Word 2010 installed on my machine, but I can't seem to get the script to open the docs. Here is the script
$path = "C:\MyPath"
Add-Type -AssemblyName Microsoft.Office.Interop.Word
$wordFiles = Get-ChildItem -Path $path -include *.doc, *.docx -recurse
$objWord = New-Object -ComObject "word.application"
$objWord.visible = $false
foreach($wd in $wordFiles)
{
$doc = $objWord.documents.open($wd.fullname)
#InsertProcessingFunctionsHere
$doc.Save()
$objWord.Documents.Close()
}
$objWord.Quit()
I try and run this, and the error I get back from PowerShell is:
Exception calling "Open" with "1" argument(s): "Command failed"
At C:\Scripts\Process-WordDocs.ps1:10 char:31
+ $doc = $objWord.documents.open <<<< ($wd.fullname)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
You cannot call a method on a null-valued expression.
At C:\Scripts\Process-WordDocs.ps1:13 char:10
+ $doc.Save <<<< ()
+ CategoryInfo : InvalidOperation: (Save:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Exception calling "Close" with "0" argument(s): "This method or property is not available because a document window is not active."
At C:\Scripts\Process-WordDocs.ps1:14 char:25
+ $objWord.Documents.Close <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
MSDN states that documents.open only requires 1 argument, and the rest are optional. However, a C# example I have seen on the net, showed passing a "ReadOnly: False" parameter to documents.open. Stepping through the script in the ISE Debugger, I can see $wd.fullname is there and points to a valid file, so I am completely unclear why it is not opening. At first, I thought this was because I was using a 64-bit version of the OS (32-bit version of Office), but attempting the script from a 32-bit PowerShell Session resulted in the same error. Anyone have any insight here as to why this may be happening, and how I can fix it? I would prefer all the processing to happen invisible to the user. Any help would be greatly appreciated. Thank you in advance for your time.
I think you want to close the document using $doc.close() instead of $objWord.Documents.Close()