New-CIMInstance dosent trigger try catch - powershell

why did the catch block
$ComputerName = "server"
try {
#Hostname Abfragen der fürs CMI Query passt
$OptDCOM = New-CimSessionOption -Protocol Dcom
$CimSessionDCOM = New-CimSession -ComputerName $ComputerName -SessionOption $OptDCOM
}
catch{
Write-Host "Fehler beim CIM-Instance mit DCOM: $ComputerName"
$array += $_.Exception.Message
$BS = "PSR"
}
$BS
doesnt trigger ?
got the following error:
New-CimSession : Der RPC-Server ist nicht verfügbar.
In Zeile:6 Zeichen:23
+ ... ssionDCOM = New-CimSession -ComputerName $ComputerName -SessionOption ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [New-CimSession], CimException
+ FullyQualifiedErrorId : HRESULT 0x800706ba,Microsoft.Management.Infrastructure.CimCmdlets.NewCimSessionCommand
+ PSComputerName :
But nothing in the catch-Block happen, i need to change to PS-Remoting when this above failed.
Thanks

Add -ErrorAction Stop
$CimSessionDCOM = New-CimSession -ComputerName $ComputerName -SessionOption $OptDCOM -ErrorAction Stop

Related

Powershell SSH credentials

I have this script for automation execute command on multiple machines but appear one problem when I try to force user to enter credential:
Write-Host "Enter credentials!" -ForegroundColor Green
$user1 = Read-Host "user"
$pwd1 = Read-Host "pass" -AsSecureString
Write-Host "type command" -ForegroundColor Cyan
Write-Host "--------------" -ForegroundColor Cyan
Write-Host "example: shutdown -f -r -t 0" -ForegroundColor Cyan
$Command1 = Read-Host -Prompt "Comanda"
$Computers = Get-Content -Path C:\Users\Meo\Desktop\ipMachine.txt | Where-Object { $_ -match '\S' }
foreach($Computer in $Computers){
Write-Host $Computer
$User = "$user1"
$pwd1_text = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pwd1))
$secpasswd = ConvertTo-SecureString $pwd1 -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential ($User, $secpasswd)
$Command1 = "$Command"
Write-Host $Command
Get-SSHTrustedHost | Remove-SSHTrustedHost
$SessionID = New-SSHSession -ComputerName $Computer -Credential $Credentials -AcceptKey:$true
Invoke-SSHCommand -Index $sessionid.sessionid -Command $Command
}
return ( if I put credential in script it works very well.. any ideea? thx)
New-SSHSession : Permission denied (keyboard-interactive).
At line:26 char:14
+ ... SessionID = New-SSHSession -ComputerName $Computer -Credential $Crede ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : SecurityError: (Renci.SshNet.SshClient:SshClient) [New-SSHSession], SshAuthenticationException
+ FullyQualifiedErrorId : SSH.NewSshSession
Invoke-SSHCommand : Cannot bind argument to parameter 'SessionId' because it is null.
At line:28 char:26
+ Invoke-SSHCommand -Index $sessionid.sessionid -Command $Command
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-SSHCommand], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Invoke-SSHCommand
```

Add specific printer to multiple servers

I am new to powershell and would like to create a tool to add a single printer to multiple servers.
Here is my code so far:
$printer = read-host "Please enter the printer name"
$ip = read-host "Please enter the printer IP"
foreach ($server in #("NPARTS20SVR",
"NPARTS21SVR",
"NPARTS22SVR",
"NPARTS23SVR",
"NPARTS24SVR")) {
Add-PrinterPort -ComputerName $server -Name $ip -PrinterHostAddress $ip
Add-Printer -ComputerName $server -ConnectionName $printer -PortName $ip -Comment $ip
}
Here is the error I am getting:
Add-PrinterPort : An error occurred while performing the specified operation. See the error details for more
information.
At \\gogo\Software\HELP\NewBuild\PreDomain\Sham scripts\AddPrinterSVR.ps1:14 char:7
+ Add-PrinterPort -ComputerName $server -Name $ip -PrinterHostAdd ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (MSFT_PrinterPortTasks:ROOT/StandardCimv2/MSFT_PrinterPortTasks) [Add-Prin
terPort], CimException
+ FullyQualifiedErrorId : HRESULT 0x8007011b,Add-PrinterPort
Add-Printer : Parameter set cannot be resolved using the specified named parameters.
At \\gogo\Software\HELP\NewBuild\PreDomain\Sham scripts\AddPrinterSVR.ps1:15 char:7
+ Add-Printer -ComputerName $server -ConnectionName $printer -Por ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Add-Printer], ParameterBindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Add-Printer

Powershell Script - Re-Prompt Password Screen If PW is İncorrect

I have a script that will change all local administrator passwords with the below script. Script will prompt password for each server. (all servers have different passwords)
I want to re-prompt the credential screen if user enters wrong password but I couldn't handle it.
$servers = Get-Content "C:\Users\Administrator\Desktop\Scripts\TestServers.txt"
foreach($server in $servers)
{
$pingtest = Test-Connection -ComputerName $server -Quiet -Count 1 -ErrorAction SilentlyContinue
if($pingtest)
{
Write-Host($server + " is online")
try
{
$ServerSessions = New-PSSession -ComputerName $server -Credential 'Administrator'
}catch [System.UnauthorizedAccessException]
{
Write-Host("Credential is incorrect! Try again")
$ServerSessions = New-PSSession -ComputerName $server -Credential 'Administrator'
}
Invoke-Command -Session $ServerSessions -ScriptBlock {
# Windows Server Versiyonunu check edip parolayı ona göre set etmek için
Get-ComputerInfo | select WindowsProductName, WindowsVersion, OsHardwareAbstractionLayer
$Password = Read-Host -AsSecureString
$UserAccount = Get-LocalUser -Name "Administrator"
$UserAccount | Set-LocalUser -Password $Password
}
else
{
Write-Host($server + " is offline, nothing to do")
}
}
}
I got this error when running the script:
<IP_Address> is online
New-PSSession : [<IP_Address>] Connecting to remote server <IP_Address> failed with the following error message : Access is denied. For more information, see the
about_Remote_Troubleshooting Help topic.
At line:12 char:31
+ ... rSessions = New-PSSession -ComputerName $server -Credential 'Administ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed
Invoke-Command : Cannot validate argument on parameter 'Session'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At line:22 char:37
+ Invoke-Command -Session $ServerSessions -ScriptBlock {
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-Command], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
else : The term 'else' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path
is correct and try again.
At line:30 char:9
+ else
+ ~~~~
+ CategoryInfo : ObjectNotFound: (else:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Write-Host($server + " is offline, nothing to do")
If I use correct password, the script works fine.
Update
Solution
Below method works but I couldn't be able to handle catch statement with catch [System.UnauthorizedAccessException]. Instead I used catch [Exception]. It is not a good solution but it works fine for me now.
$servers = Get-Content "C:\Users\Administrator\Desktop\Scripts\TestServers.txt"
foreach($server in $servers)
{
$pingtest = Test-Connection -ComputerName $server -Quiet -Count 1 -ErrorAction SilentlyContinue
if($pingtest)
{
Write-Host($server + " is online")
$Creds = Get-Credential 'Administrator'
do{
try
{
$ServerSessions = New-PSSession -ComputerName $server -Credential $Creds -ErrorAction Stop
Write-Host ("$ServerSessions")
}catch [Exception]
{
Write-Host("Credential is incorrect! Try again")
$Creds = Get-Credential 'Administrator'
}
}while(!$ServerSessions)
Invoke-Command -Session $ServerSessions -ScriptBlock {
# Windows Server Versiyonunu check edip parolayı ona göre set etmek için
Get-ComputerInfo | select WindowsProductName, WindowsVersion, OsHardwareAbstractionLayer
$Password = Read-Host -AsSecureString
$UserAccount = Get-LocalUser -Name "Administrator"
$UserAccount | Set-LocalUser -Password $Password
}
}
else {
Write-Host($server + " is offline, nothing to do")
}
}
Try/catch doesn't work if it is not a stopping error, so add the -ErrorAction Stop parameter to your session, and then wrap that try/catch inside a Do/While loop based on if you have a session or not and get new creds in the Catch part.
$Creds = Get-Credentials 'Administrator'
Do{
try
{
$ServerSessions = New-PSSession -ComputerName $server -Credential $Creds -ErrorAction Stop
}catch [System.UnauthorizedAccessException]
{
Write-Host("Credential is incorrect! Try again")
$Creds = Get-Credentials 'Administrator'
}
}While(!$ServerSessions)
Your curly braces for the if statement were incorrect. This is why properly indenting your code is of importance.
To retry the authentication, use a while loop that will keep looping until a new session is established. For example:
$servers = Get-Content "C:\Users\Administrator\Desktop\Scripts\TestServers.txt"
foreach($server in $servers)
{
$pingtest = Test-Connection -ComputerName $server -Quiet -Count 1 -ErrorAction SilentlyContinue
if($pingtest)
{
Write-Host "$server is online"
while ($True) {
try
{
$Cred = Get-Credential -UserName 'Administrator'
$ServerSession = New-PSSession -ComputerName $server -Credential $Cred
break
}catch [System.UnauthorizedAccessException]
{
Write-Host "Credential is incorrect! Try again"
}
}
try {
Invoke-Command -Session $ServerSession -ScriptBlock {
# Windows Server Versiyonunu check edip parolayı ona göre set etmek için
Get-ComputerInfo | select WindowsProductName, WindowsVersion, OsHardwareAbstractionLayer
$Password = Read-Host -AsSecureString
$UserAccount = Get-LocalUser -Name "Administrator"
$UserAccount | Set-LocalUser -Password $Password
}
finally {
Remove-PSSession $ServerSession
}
}
else {
Write-Host "$server is offline, nothing to do"
}
}

Why do I receive an "RPC error" when using Get-WmiObject on a Netapp SVM

How can i get this to show me who's using the shares on our NETAPP.
$computer = "gozer"
$namespace = "root\CIMV2" # note to self find out if this is correct
$userSessions = Get-WmiObject -class Win32_ServerConnection -computername $computer -namespace $namespace
if($userSessions -ne $null)
{
Write-Host "The following users are connected to your PC: "
foreach ($userSession in $userSessions)
{
$userDetails = [string]::Format("User {0} from machine {1} on share: {2}",
$userSession.UserName, $userSession.ComputerName, $userSession.ShareName)
Write-Host $userDetails
}
Read-Host
}
exit
the error i receive when i run this pointing at a NETAPP SVM is:
Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At C:\test\whos-using-the-share.ps1:3 char:17
+ $userSessions = Get-WmiObject -class Win32_ServerConnection -computername $compu ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Get-WmiObject], COMException
+ FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

Check/read registry key value on remote computer with local admin credential

How to check registry key value on computer which is not in domain??
I think that I must use local admin credential for this but I dont know how
I tried this:
$user = "admin"
$password = "pass" | ConvertTo-SecureString -asPlainText -Force
$computer = "computer"
$domain=$computer
$username = $domain + "\" + $user
$Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $username,$password
$key = '\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters'
$valuename = 'DiskSpaceThreshold'
$wmi = Get-Wmiobject -list "StdRegProv" -namespace root\default -Computername $computer -Credential $Credential
$value = $wmi.GetStringValue($HKEY_Local_Machine,$key,$valuename).svalue
$wmi
$value
But the result:
Get-Wmiobject : Could not get objects from namespace root\default. Serwer RPC jest niedostępny. (Wyjątek od HRESULT: 0x800706BA) At line:12 char:8
+ $wmi = Get-Wmiobject -list "StdRegProv" -namespace root\default -Comp ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [Get-WmiObject], COMException
+ FullyQualifiedErrorId : INVALID_NAMESPACE_IDENTIFIER,Microsoft.PowerShell.Commands.GetWmiObjectCommand You cannot call a method on a null-valued expression. At line:13 char:1
+ $value = $wmi.GetStringValue($HKEY_Local_Machine,$key,$valuename).sva ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
__GENUS : 2
__CLASS : __PARAMETERS
__SUPERCLASS :
__DYNASTY : __PARAMETERS
__RELPATH :
__PROPERTY_COUNT : 2
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH : ReturnValue : 6 uValue : PSComputerName :
So I tried something else
# file with computer name
$computers = Get-Content F:\IT\!Set_NTP_Time\ReadRegistry\servers.txt | ?{$_ -notmatch "^#"};
#Registry Hives
[long]$HIVE_HKROOT = 2147483648
[long]$HIVE_HKCU = 2147483649
[long]$HIVE_HKLM = 2147483650
[long]$HIVE_HKU = 2147483651
[long]$HIVE_HKCC = 2147483653
[long]$HIVE_HKDD = 2147483654
# registry
$HKLM = 2147483650
$main = "Localmachine"
$keyPath = "System\CurrentControlSet\Services\W32Time"
$keyName = "Start"
#$computer ='.'
$reg = [WMIClass]"ROOT\DEFAULT:StdRegProv"
$Key = "W32Time"
#$Value = "HistoryBufferSize"
#$results = $reg.GetDWORDValue($HKEY_LOCAL_MACHINE, $Key, $keyName)
#"Current History Buffer Size: {0}" -f $results.uValue
<#
Param($computer)
$HKEY_Local_Machine = 2147483650
$reg = [WMIClass]"\\$computer\ROOT\DEFAULT:StdRegProv"
$Key = "SOFTWARE\Wow6432Node\Symantec\Symantec Endpoint Protection\CurrentVersion\SharedDefs"
$ValueName = "DEFWATCH_10"
$results = $reg.GetStringValue($HKEY_LOCAL_MACHINE, $Key, $ValueName)
write $results.sValue
#>
# credentials
$user = "admin"
$user1 = "admin1"
$password = "pass" | ConvertTo-SecureString -asPlainText -Force
# Start processing
foreach($computer in $computers) {
$domain=$computer
$username = $domain + "\" + $user
$username1 = $domain + "\" + $user1
$Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $username,$password
$Credential1 = New-Object System.Management.Automation.PSCredential -ArgumentList $username1,$password
try {
if (($computer -eq "comp1") -or ($computer -eq "comp2") -or ($computer -eq "name_of_computer") -or ($computer -eq "other_computer")) {
#$wmi = Get-Wmiobject -list "StdRegProv" -namespace root\default -Computername $computer -Credential $Credential1
#$value = $wmi.GetStringValue($HKLM,$keyPath,$keyName).svalue
#Write-Host -ForegroundColor DarkYellow $computer $value
#$value = Invoke-Command -Scriptblock {Get-Item $HKLM,$keyPath,$keyName} -Computername $computer -Credential $Credential1
$reg = Get-WmiObject -List -Namespace root\default -ComputerName $Computer -Credential $Credential1 | Where-Object {$_.Name -eq "StdRegProv"}
#$HKLM = 2147483650
#$value = $reg.GetStringValue($HKLM,$keyPath,$keyName).sValue
$value = $reg.GetDWORDValue($HKEY_LOCAL_MACHINE, $Key, $keyName)
Write-Host -ForegroundColor DarkYellow $computer $reg $value
} else {
#$wmi = Get-Wmiobject -list "StdRegProv" -namespace root\default -Computername $computer -Credential $Credential
#$value = $wmi.GetStringValue($HKLM,$keyPath,$keyName).svalue
#Write-Host -ForegroundColor DarkYellow $computer $value
#$value = Invoke-Command -Scriptblock {Get-Item $HKLM,$keyPath,$keyName} -Computername $computer -Credential $Credential
$reg = Get-WmiObject -List -Namespace root\default -ComputerName $Computer -Credential $Credential | Where-Object {$_.Name -eq "StdRegProv"}
#$HKLM = 2147483650
#$value = $reg.GetStringValue($HKLM,$keyPath,$keyName).sValue
$value = $reg.GetDWORDValue($HKEY_LOCAL_MACHINE, $Key, $keyName)
Write-Host -ForegroundColor DarkYellow $computer $reg $value
}
<#
if($value -eq 2)
{
Write-Host -ForegroundColor DarkYellow $computer "YES"
} else {
Write-Host -ForegroundColor Red $computer "NO"
}
#>
} catch {
Write-Host -ForegroundColor Red "$computer access denied.$_";
}
}
Result for this script
comp1 \COMP1\ROOT\default:StdRegProv System.Management.ManagementBaseObject
comp2 \COMP2\ROOT\default:StdRegProv System.Management.ManagementBaseObject
comp3 \COMP3\ROOT\default:StdRegProv System.Management.ManagementBaseObject
Personally, as I am used to use powershell remoting to gather information from remote machines, I would proceed like this:
Establish remote PS session
Run script on remote machine
Profit
So in your case, something like (If you are retrieving a value named DiskSpaceThreshold inside of HKLM:\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters)
$user = "admin"
$password = "pass" | ConvertTo-SecureString -asPlainText -Force
$computer = "computer"
$domain=$computer
$username = $domain + "\" + $user
$Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $username,$password
$session = New-PSSession $computer -Credential $Credential
$r = Invoke-Command -Session $session -ScriptBlock { Get-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters -Name "DiskSpaceThreshold" }
Remove-PSSession $session
Write-Host $r.DiskSpaceThreshold
The effect of trying to run the script from P-L user post
New-PSSession : [computer] Connecting to remote server computer failed with the following error message : WinRM cannot process the
request. The following error with errorcode 0x80090311 occurred while using Kerberos authentication: There are currently no
logon servers available to service the logon request.
Possible causes are:
-The user name or password specified are invalid.
-Kerberos is used when no authentication method and no user name are specified.
-Kerberos accepts domain user names, but not local user names.
-The Service Principal Name (SPN) for the remote computer name and port does not exist.
-The client and remote computers are in different domains and there is no trust between the two domains.
After checking for the above issues, try the following:
-Check the Event Viewer for events related to authentication.
-Change the authentication method; add the destination computer to the WinRM TrustedHosts configuration setting or use HTT
PS transport.
Note that computers in the TrustedHosts list might not be authenticated.
-For more information about WinRM configuration, run the following command: winrm help config. For more information, see
the about_Remote_Troubleshooting Help topic.
At line:9 char:12
+ $session = New-PSSession $computer -Credential $Credential
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTran
sportException
+ FullyQualifiedErrorId : AuthenticationFailed,PSSessionOpenFailed
Invoke-Command : Cannot validate argument on parameter 'Session'. The argument is null or empty. Provide an argument that is
not null or empty, and then try the command again.
At line:10 char:30
+ $r = Invoke-Command -Session $session -ScriptBlock { Get-ItemProperty -Path HKLM ...
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-Command], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
Remove-PSSession : Cannot validate argument on parameter 'Id'. The argument is null. Provide a valid value for the argument,
and then try running the command again.
At line:11 char:18
+ Remove-PSSession $session
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Remove-PSSession], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.RemovePSSessionCommand
The username and password are good.