I have powershell function error, the not execute - powershell

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­

Related

I can t set up a network firewall rule with powershell

Hi got an issue to turn on a firewall rule :
My goal is to set up a network firewall rule on my public profile for a specific displaygroup with a range of ip networks (variable).
commmand :
https://learn.microsoft.com/en-us/powershell/module/netsecurity/set-netfirewallrule?view=windowsserver2022-ps
I ve tried to switch the variable and always the same issue below :
$IPAddresses = #('192.168.124.0/22','192.168.125.0/22','192.168.127.0/22','192.168.136.0/22','192.168.138.0/22','192.168.139.0/22')
set-netfirewallrule -DisplayGroup "Recherche du réseau" -Enabled True -Profile Public -RemoteAddress $IPAddresses -LocalAddress $IPAddresses
set-netfirewallrule : Impossible de combiner des points de terminaison logiques (tuples de confiance) avec des adresses ou des ports spécifiques.
Au caractère Ligne:1 : 1
+ set-netfirewallrule -DisplayGroup "Recherche du réseau" -Enabled True ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument : (MSFT_NetFirewal...ystemName = ""):root/standardcimv2/MSFT_NetFirewallRule) [Set-NetFirewallRule], CimException
+ FullyQualifiedErrorId : HRESULT 0x80070057,Set-NetFirewallRule
set-netfirewallrule : Impossible de combiner des points de terminaison logiques (tuples de confiance) avec des adresses ou des ports spécifiques.
Au caractère Ligne:1 : 1
+ set-netfirewallrule -DisplayGroup "Recherche du réseau" -Enabled True ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument : (MSFT_NetFirewal...ystemName = ""):root/standardcimv2/MSFT_NetFirewallRule) [Set-NetFirewallRule], CimException
+ FullyQualifiedErrorId : HRESULT 0x80070057,Set-NetFirewallRule
If someone could help me ^^
Thks

POWERSHELL - Define a default parameter set name ONLY if a parameter is specified

I have this code here (I simplified) :
Enum Region {
AU
BE
BR
CA
}
Function Get-AccByCountry
{
[CmdletBinding(DefaultParameterSetName='With_Specific_Countries')]
PARAM (
[Parameter(Mandatory=$false,
ParameterSetName='With_Specific_Countries')]
[Region[]]
$Regions,
[Parameter(Mandatory=$false,
ParameterSetName='Without_Specific_Countries')]
[Region[]]
$NotRegions
)
#BEGIN{}
PROCESS
{
Write-Verbose -Message "Starting global process"
IF($Regions){
foreach($r in $Regions){
[String]$r = $r
Get-AccByCountryLocalized $r -Verbose
}
}ELSEIF($NotRegions){
foreach($PR in [Enum]::GetValues([type]"Region")){
[String]$PR = $PR
IF($NotRegions -notcontains $PR)
{
$PR
Get-AccByCountryLocalized $PR -Verbose
}
}
}ELSE{
Get-AccByCountryGlobal -Verbose
}
}
#END{}
}
So I can call Get-AccByCountry either with no parameters specified, regions specified, of the regions I don't want specified (3 possibilities).
These 3 calls work :
Get-AccByCountry
Get-AccByCountry -Region AU,BE
Get-AccByCountry -NotRegions AU,BE
But when I try :
Get-AccByCountry AU,BE
It doesn't work ! It gives me this error (in French) :
Get-AccByCountry : Impossible de trouver un paramètre positionnel acceptant l'argument « System.Object[] ».
Au caractère Ligne:1 : 1
+ Get-AccByCountry CA,AU
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument : (:) [Get-AccByCountry], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Get-AccByCountry
I specified the DefaultParameterSetName, but it's not taken into account.
I want that my function to take the set 'With_Specific_Countries' everytime I give a parameter without specifying a set.
How should I do ?

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?

Invoke-Command create new object

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?

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)