Invoke-Command create new object - powershell

I've got a problem to create new object with Invoke-Command:
$a = 'TEST'
Invoke-Command -ComputerName $computer -Credential $cred -ScriptBlock {
param($a, $b, $c)
$o = New-Object -ComObject Outlook.Application
echo $a
} -ArgumentList ($a, $b, $c)
I'm getting the following error:
La récupération de la fabrique de classes COM pour le composant avec le CLSID
{0006F03A-0000-0000-C000-000000000046} a échoué en raison de l'erreur suivante :
80080005 Échec de l'exécution du serveur (Exception de HRESULT : 0x80080005
(CO_E_SERVER_EXEC_FAILURE)).
+ CategoryInfo : ResourceUnavailable: (:) [New-Object], COMException
+ FullyQualifiedErrorId : NoCOMClassIdentified,Microsoft.PowerShell.Commands.NewObjectCommand
TEST
where the trailing "TEST" is the output of echo $a.
I can't create the new object remotly. can you help me?

Related

How to make a PowerShell FTPS script (SSL) to upload a single file?

I need a script to help me for uploading a single file, to a cloud.
I found some answers with the protocol SFTP (SSH), but I cannot find a script working with FTPS (SSL).
I have tried this script, but it doesn't work:
Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"
$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.ParseUrl("**ftps**://**login**:**password**#**ipoftheremoteserver**:990/")
$session = New-Object WinSCP.Session
$session.Open($sessionOptions)
$session.PutFiles("D:\QAPPLI\Quadra\DATABASE\PAIE\000001\qpaie.mdb", "/FOLDER1/08h00").Check()
$session.Dispose()
I have this error:
PS C:\Windows\system32> D:\Script\08h00_000001_Client1_to_ftps.ps1 Exception lors de l'appel de « Check » avec « 0 » argument(s) :
« Erreur lors du transfert du fichier 'D:\QAPPLI\Quadra\DATABASE\PAIE\000001\qpaie.mdb'.
Server sent passive reply with unroutable address 172.16.59.131, using host address instead.
Copie de fichiers vers le coté distant échouée.
Filename invalid 
Au niveau de D:\08h00_000001_Client1_to_ftps.ps1 : 8
Caractère : 85
+ $session.PutFiles("D:\QAPPLI\Quadra\DATABASE\PAIE\000001\qpaie.mdb", "/FOLDER1/08h00").Check <<<< ()
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
Translated to English:
D:Script08h00_000001_Client1_to_ftps.ps1 Exception when calling "Check" with "0" argument (s): «"Error transferring file ' D:QAPPLIQuadraDATABASEPAIE000001qpaie.mdb '. Server sent passive reply with unroutable address 172.16.59.131, using host address instead.
Copying files to the failed remote side.
Filename Invalid
at D:08h00_000001_Client1_to_ftps.ps1:8 character: 85 + $session. PutFiles ( "D:QAPPLIQuadraDATABASEPAIE000001qpaie.mdb", "/FOLDER1/08h00"). Check < < < () + CategoryInfo: NotSpecified: (:) [], MethodInvocationException + FullyQualifiedErrorId: DotNetMethodException
Many thanks for your help.
The remotePath (second) argument of Session.PutFiles is:
Full path to upload the file to.
While you seem to pass in a path to a folder only, not full path to a file.
This should be correct:
$session.PutFiles(
"D:\QAPPLI\Quadra\DATABASE\PAIE\000001\qpaie.mdb", "/FOLDER1/08h00/qpaie.mdb").Check()
Using the .Net Framework's FTPWebRequest class from PowerShell, with the EnableSsl property to enable FTPS
[Net.ServicePointManager]::ServerCertificateValidationCallback={$true}
$Dir = "D:\FolderWithBackupFilesToMove"
foreach($item in (dir $dir))
{
write-output "-------------"
$fileName = $item.FullName
write-output $fileName
$ftp = [System.Net.FtpWebRequest]::Create("ftp://some.ftp.server.com/someRootFolder/"+$item.Name)
$ftp = [System.Net.FtpWebRequest]$ftp
$ftp.UsePassive = $true
$ftp.UseBinary = $true
$ftp.EnableSsl = $true
$ftp.Credentials = new-object System.Net.NetworkCredential("UserName","Password")
$ftp.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$rs = $ftp.GetRequestStream()
$reader = New-Object System.IO.FileStream ($fileName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read)
[byte[]]$buffer = new-object byte[] 4096
[int]$count = 0
do
{
$count = $reader.Read($buffer, 0, $buffer.Length)
$rs.Write($buffer,0,$count)
} while ($count -gt 0)
$reader.Close()
$rs.Close()
write-output "+transfer completed"
$item.Delete()
write-output "+file deleted"
}

Set EntityReference attribute to not working Microsoft.Xrm.Data.PowerShell

I cannot update a theme by PowerShell using Microsoft.Xrm.Data.PowerShell.
The following code is not working:
#Get Theme
$res = Get-CrmRecords -Conn $connection -EntityLogicalName theme -FilterAttribute name -FilterOperator eq -FilterValue $nameOfTheme -Fields themeid, name, logoid, isdefaulttheme, logotooltip, navbarbackgroundcolor, navbarshelfcolor, headercolor, globallinkcolor, selectedlinkeffect, hoverlinkeffect, processcontrolcolor, defaultentitycolor, defaultcustomentitycolor, controlshade, controlborder
$ImportedTheme = $res.CrmRecords[0]
#Get Resource web
$resLogo = Get-CrmRecords -Conn $connection -EntityLogicalName webresource -FilterAttribute name -FilterOperator eq -FilterValue "LogoName"
$ImportedLogo = $resLogo.CrmRecords[0]
$ERLogo = (New-CrmEntityReference -EntityLogicalName webresource -Id $ImportedLogo.webresourceid)
#Update Theme
$ImportedTheme.logoid = $ERLogo
Set-CrmRecord -Conn $connection -CrmRecord $ImportedTheme
This will given an error:
Impossible d'appeler une méthode dans une expression Null.
Au caractère C:\Users\il...ll\Microsoft.Xrm.Data.PowerShell.psm1:628 : 16
+ if($crmFieldValue -eq $null)
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation : (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Le cast spécifié n'est pas valide. Au caractère
C:\Users\il...ll\Microsoft.Xrm.Data.PowerShell.psm1:773 : 9
+ throw $conn.LastCrmException
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], InvalidCastException
+ FullyQualifiedErrorId : Le cast spécifié n'est pas valide.
I think the problem comes from this verification in this part of code of Xrm.Data.PowerShell:
if($crmFieldValue -eq $null) { Write-Host "$crmFieldValue -eq $null"
$newfield.Type = [Microsoft.Xrm.Tooling.Connector.CrmFieldType]::Raw $value = $null }
I cannot find a solution. Do you have any idea?

How to reset a Domain User Password with Remote Powershell

I want to reset my own Active Directory Password on a remote Machine (different domain).
If I use the following code snippet locally it works perfectly:
param(
[string]$oldPassword = $(Read-Host "Old password"),
[string]$newPassword = $(Read-Host "New password")
)
$ADSystemInfo = New-Object -ComObject ADSystemInfo
$type = $ADSystemInfo.GetType()
$user = [ADSI] "LDAP://$($type.InvokeMember('UserName', 'GetProperty', $null, $ADSystemInfo, $null))"
$user.ChangePassword($oldPassword, $newPassword)
Running following snippet on the remote machine fails:
$ADSystemInfo = New-Object -ComObject ADSystemInfo
$type = $ADSystemInfo.GetType()
Invoke-Command -Session $Session -ScriptBlock {
param($rtype, $RemoteADSystemInfo, $OldPassword)
$user = [ADSI] "LDAP://$($rtype.InvokeMember('UserName', 'GetProperty', $null, $RemoteADSystemInfo, $null))"
$user.ChangePassword($OldPassword , "TestPa$$w0rd"")
} -ArgumentList $type,$ADSystemInfo,$Password
Error Message: Method invocation failed because
[Deserialized.System.RuntimeType] does not contain a method named
'InvokeMember'.
+ CategoryInfo : InvalidOperation: (InvokeMember:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
+ PSComputerName : test.test.domain The following exception occurred while retrieving member "ChangePassword": "Unknown error (0x80005000)"
+ CategoryInfo : NotSpecified: (:) [], ExtendedTypeSystemException
+ FullyQualifiedErrorId : CatchFromBaseGetMember
+ PSComputerName : test.test.domain

I have powershell function error, the not execute

I am a beginner in powershell script. I have a diskcap function to avoid retyping the text. but I get errors.
Function DiskCap­ {
return
(write-host "calcule de l'espace libre avant le nettoyage.")
($FreeSpace = (Get-WmiObject win32_logicaldisk | where { $_.DeviceID -eq $env:SystemDrive }).FreeSpace)
($yourdisk = Get-WmiObject Win32_volume)
ForEach ($Item in $YourDisk) {
"{0,-8} {1,2}" -f $Item.Name, (Format-DiskSize $Item.Capacity).phase
}
}
pause
#Write-Host $(diskcap)
[ERROR] diskcap : Le terme «diskcap» n'est pas reconnu comme nom d'applet de commande, [ERROR] fonction, fichier de script ou
programme exécutable. Vérifiez l'orthographe du nom, [ERROR] ou si un
chemin d'accès existe, vérifiez que le chemin d'accès est correct et
[ERROR] réessayez. [ERROR] Au caractère
C:\Users\SoutienInformatique\Downloads\Ninite\CLEAN.ps1:53 : 15
[ERROR] + Write-Host $(diskcap) [ERROR] + ~~~~~~~
[ERROR] + CategoryInfo : ObjectNotFound: (diskcap:String)
[], CommandNotFoundEx [ERROR] ception [ERROR] +
FullyQualifiedErrorId : CommandNotFoundException [ERROR]
The following code doesn't throw the "'diskcap' is not recognized as the name of a cmdlet" error.
You don't need to add the write-host $(diskcap) at the end to get the output of the function. You can just call it. The parenthesis is also not nessecary around each statement.
function DiskCap­ {
write-host "calcule de l'espace libre avant le nettoyage."
$FreeSpace = (Get-WmiObject win32_logicaldisk | Where-Object { $_.DeviceID -eq $env:SystemDrive }).FreeSpace
$yourDisk = Get-WmiObject Win32_volume
foreach ($Item in $yourDisk)
{
"{0,-8} {1,2}" -f $Item.Name, (Format-DiskSize $Item.Capacity).phase
}
}
Pause
DiskCap­

What is the need of using 'put' method to set the value of a property through powershell

I tried the following cases :
$Localhst = $env:ComputerName;
$comp = [ADSI]('WinNT://'+$Localhst+',computer');
$user = $comp.Create('User', 'account24');
$user.SetPassword('Welcome1$');
$user.Description = "Created through powershell script client";
$user.SetInfo();
I am getting the following exception :
Error Occurred while executing powershell command Exception calling "SetInfo" with "0" argument(s): "The account already exists. (Exception from HRESULT: 0x8007
08B0)"
But when I am using put method it is working fine :
$Localhst = $env:ComputerName;
$comp = [ADSI]('WinNT://'+$Localhst+',computer');
$user = $comp.Create('User', 'account24');
$user.SetPassword('Welcome1$');
$user.put("Description","Created through powershell script client");
$user.SetInfo();
What is the difference between using put method to set the value and setting the value directly?
I use the same code but receive a different error
$Localhst = $env:ComputerName;
$comp = [ADSI]('WinNT://'+$Localhst+',computer');
$user = $comp.Create('User', 'account24');
$user.SetPassword('Welcome1$');
$user.Description = "Created through powershell script client";
$user.SetInfo();
Produce
$user.SetInfo();
Exception lors de la définition de « Description » : « Impossible de définir la propriété Value de l'objet PSMemberInfo de type « System.Management.Automation.PSMethod ». »
Au caractère Ligne:5 : 1
+ $user.Description = "Created through powershell script client";
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenSetting
Exception lors de l'appel de « SetInfo » avec « 0 » argument(s) : « Accès refusé.
 »
Au caractère Ligne:6 : 1
+ $user.SetInfo();
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : CatchFromBaseAdapterMethodInvokeTI
The message is in French but it significate unable to define the property like this. But if I run it as administrator it create the user (with no description)