Regex Match for first line of Powershell Error Output - regex

I am using new-pssession to connect to machines and am storing any errors in a value specified by the -errorVariable paramater. I want to call this variable later for output but on want to show the the first line, minus the comp name in brackets.
Heres an example of what i get.
New-PSSession : [ABCGFAXYZUT579] Connecting to remote server ABCGFAXYZUT579 failed with the
following error message : WinRM cannot complete the operation. Verify that the
specified computer name is valid, that the computer is accessible over the network, and that a
firewall exception for the WinRM service is enabled and allows access from this
computer. By default, the WinRM firewall exception for public profiles limits access to remote
computers within the same local subnet. For more information, see the
about_Remote_Troubleshooting Help topic.
At line:1 char:1
+ New-PSSession -ComputerName ABCGFAXYZUT579 -ErrorVariable errors912 ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-
PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : WinRMOperationTimeout,PSSessionOpenFailed
I have tried passing the variable to select-string to get only what i need but everything i have tried still gives me this
[ABCGFAXYZUT579] Connecting to remote server ABCGFAXYZUT579 failed with the following error
message : WinRM cannot complete the operation. Verify that the specified computer name
is valid, that the computer is accessible over the network, and that a firewall exception for
the WinRM service is enabled and allows access from this computer. By default, the
WinRM firewall exception for public profiles limits access to remote computers within the same
local subnet. For more information, see the about_Remote_Troubleshooting Help topic.
I have also tried splitting it into seperate lines like this
($errors912 -split '\r?\n' -ne '') and piping to select-string but i still get the above returned.
is there an easy way to get everything after the first white space and before the first period? leaving this?
Connecting to remote server ABCGFAXYZUT579 failed with the following error
message : WinRM cannot complete the operation.

$NewSession = New-PSSession -ComputerName ABCGFAXYZUT579 -ErrorVariable errors912 -ErrorAction SilentlyContinue
if ( $errors912.Count -gt 0 ) {
[string]$errors912 -replace "^(\[.*?\] )|(?<=\.).*"
}
Connecting to remote server ABCGFAXYZUT579 failed with the following error message : The WinRM client cannot process the request.
The $errors912.Count -gt 0 condition is equivalent to $null -eq $NewSession.
Please go to some on-line regex tester/debugger e.g. https://regex101.com/ for the regex explanation.

Related

AWS Lambda Powershell to create mailbox in Hybrid(run powershell commands in both Office 365 and On-Prem)

Now that AWS Lambda supports PowerShell core according to this blog, has anybody tried running PowerShell commands to create Mailbox in Hybrid env(run PS cmdlets in both On-prem and office 365 env) using lambda? I couldn't find anything online which does that. Most of the Lambda Powershell usecases seems to be related to using PowerShell scripts to automate and manage AWS resources.
I'm working on a POC for a REST service which does all of the mailbox creation operations and was planning to use API gateway to invoke lambda powershell.
I did setup my environment following aws documentation and created a PowerShell script which performs mailbox operation and created and deployed lambda. Upon testing, i'm getting the following errors while creating a PowerShell session for O365 env.
Script snippet:
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $mycreds -Authentication Basic -AllowRedirection
Write-Host "Created session for PS"
Import-PSSession $Session
Write-Host "Imported Session"
Write-Host "Getting Mailbox"
Get-Mailbox -Identity 'mailbox'
Cloudwatch Logs:
[Error] - This parameter set requires WSMan, and no supported WSMan client library was found. WSMan is either not installed or unavailable for this system.
[Information] - Created session for PS
[Error] - Cannot validate argument on parameter 'Session'. The argument is null. Provide a valid value for the argument, and then try running the command again.
[Information] - Imported Session
[Information] - Getting Mailbox
[Error] - The term 'Get-Mailbox' 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.
Wondering if anyone has tried invoking Office 365/on-prem mailbox creation PS scripts using lambda or point me to the right direction? Thanks
I would also like to know, if with AWS lambda powershell core can i winrm into another windows box so that i can execute powershell mailbox commands? According to the ans dated in 10/2018 we cannot, but wondering if anyone knows anything latest on this.
I am working the same task. API->Lambda->C#/PowerShell->Office360->CreateMailbox.
However I'm hung up on the same line as well, but slightly different message.
What do you have for a Requires line in your ps1 file?
Requires -Modules #{ModuleName='AWS.Tools.Common';ModuleVersion='4.0.5.0'}
I am assuming you are using ModuleVersion='3.3.618.0' per the linked blog post, but there is a '4.0.5.0' version available. ... However it hasn't help me yet, but perhaps it would help you. Here is link with the upgrade information. https://docs.aws.amazon.com/powershell/latest/userguide/v4migration.html

Set-AWSSamlRoleProfile fails with "Unable to set credentials: "choices" should have at least one element." error

I am trying to get a federated user access to AWS API using PowerShell. (Link provided below)
AWS is properly configured to work with AD. (It works for bunch of my colleagues)
I am using PowerShell script to access the AWS API's.
The problem occurs when I try to run the command Set-AWSSamlRoleProfile.
Error:
C:\Windows\system32> Set-AWSSamlRoleProfile -EndpointName $EndpointName -PrincipalARN $PrincipalARN -RoleARN $RoleARN -StoreAs 'SAMLUser' > $null
Set-AWSSamlRoleProfile : Unable to set credentials: "choices" should have at least one element.
At line:1 char:1
+ Set-AWSSamlRoleProfile -EndpointName $EndpointName -PrincipalARN $Pri ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (Amazon.PowerShe...leProfileCmdlet:SetSamlRoleProfileCmdlet) [Set-AWSSamlRoleProfile], ArgumentException
+ FullyQualifiedErrorId : ArgumentException,Amazon.PowerShell.Common.SetSamlRoleProfileCmdlet
Any help or guidance appreciated.
In my case, the issue was that the user (me) was not part of the group by AD.
Hope it helps someone else.

Invoke-WmiMethod : Access denied when sending message to EC2 instances

I have a PowerShell script that stops all running instances, I want to add a message that pops up inside the instance to notify the user that the instance is shutting down and if possible accept or deny that.
This is the complete code (as of right know only stops):
Get-EC2InstanceStatus | Out-File -filepath C:\Users\AGOJSO\Desktop\xd.txt
select-string -path "C:\Users\AGOJSO\Desktop\xd.txt" -Pattern 'i-.*$' | select line | out-file "C:\Users\AGOJSO\Desktop\xaxa.txt"
(Get-Content C:\Users\AGOJSO\Desktop\xaxa.txt) | ForEach-Object { $_ -replace 'InstanceId :' } > C:\Users\AGOJSO\Desktop\xaxa.txt
(Get-Content C:\Users\AGOJSO\Desktop\xaxa.txt) | ForEach-Object { $_ -replace 'Line' } > C:\Users\AGOJSO\Desktop\xaxa.txt
(Get-Content C:\Users\AGOJSO\Desktop\xaxa.txt) | ForEach-Object { $_ -replace '----' } > C:\Users\AGOJSO\Desktop\xaxa.txt
foreach ($line in [System.IO.File]::ReadLines("C:\Users\AGOJSO\Desktop\xaxa.txt")) {
Write-Host "$line"
}
$instanceIDArray = "i-0159d9e5a717cfb73", "i-012fef2b144ea0476"
( (Get-EC2Instance | ? { $_.instances.tag.value -match $instanceIDArray} ).Instances).InstanceID | Stop-EC2Instance $instanceIDArray
So now I need to interact via message with the user, I have tried it with this code with no luck, only works if I type localhost intead of the #IP:
$name = "10.115.106.46"
$msg = "Enter your message "
Invoke-WmiMethod -Path Win32_Process -Name Create -ArgumentList "msg * $msg" -ComputerName $name
Error received:
Invoke-WmiMethod : Access denied. (Exeption HRESULT: 0x80070005 (E_ACCESSDENIED))
Thanks (:
This is not unique to what you are doing with AWS instances. WMI security can get a bit finicky.
Well, that and The big drawback to the WMI cmdlets is that they use DCOM to access remote machines. DCOM isn’t firewall friendly, can be blocked by networking equipment, and gives some arcane errors when things go wrong.
Which is why in in the last few releases of Windows, CIM is being pushed.
Since PowerShellv3 CIM was the focus (it uses WSMAN vs DCOM) (PSv2 and below was all WMI), though many still continued to use WMI out of habit or the need to support v2 or below.
Even with MS Online, it's all PSCore (so learn to use it as well), and CIM focused. So, try and use Invoke-CimMethod instead.
So, give this a shot using Invoke-CimMethod instead of Invoke-WmiMethod, since DCOM requires additional host and firewall configurations in many cases.
See details on this error code here:
WMI troubleshooting
Access Denied errors that are reported by scripts and applications that access WMI namespaces and data generally fall into three categories. The following table lists the three categories of errors along with issues that might cause the errors and possible solutions.
0x80070005 – E_ACCESS_DENIED
Access denied by DCOM security.
The user does not have remote access to the computer through DCOM. Typically, DCOM errors occur when connecting to a remote computer with a different operating system version.
Give the user Remote Launch and Remote Activation permissions in dcomcnfg. Right-click My Computer-> Properties Under COM Security, click "Edit Limits" for both sections. Give the user you want remote access, remote launch, and remote activation. Then go to DCOM Config, find "Windows Management Instrumentation", and give the user you want Remote Launch and Remote Activation. For more information, see Connecting Between Different Operating Systems

Azure VM, your credentials did not work on remote desktop

I've just had a bit of fun trying to connect to a new VM I'd created, I've found loads of posts from people with the same problem, the answer details the points I've found
(1) For me it worked with
<VMName>\Username
Password
e.g.
Windows8VM\MyUserName
SomePassword#1
(2) Some people have just needed to use a leading '\', i.e.
\Username
Password
Your credentials did not work Azure VM
(3) You can now reset the username/password from the app portal. There are powershell scripts which will also allow you to do this but that shouldn't be necessary anymore.
(4) You can also try redeploying the VM, you can do this from the app portal
(5) This blog says that "Password cannot contain the username or part of username", but that must be out of date as I tried that once I got it working and it worked fine
https://blogs.msdn.microsoft.com/narahari/2011/08/29/your-credentials-did-not-work-error-when-connecting-to-windows-azure-vms/
(6) You may find links such as the below which mention Get-AzureVM, that seems to be for classic VMs, there seem to be equivalents for the resource manager VMs such as Get-AzureRMVM
https://blogs.msdn.microsoft.com/mast/2014/03/06/enable-rdp-or-reset-password-with-the-vm-agent/
For complete novices to powershell, if you do want to go down that road here's the basics you may need. In the end I don't believe I needed this, just point 1
unInstall-Module AzureRM
Install-Module AzureRM -allowclobber
Import-Module AzureRM
Login-AzureRmAccount (this will open a window which takes you through the usual logon process)
Add-AzureAccount (not sure why you need both, but I couldn’t log on without this)
Select-AzureSubscription -SubscriptionId <the guid for your subscription>
Set-AzureRmVMAccessExtension -ResourceGroupName "<your RG name>" -VMName "Windows8VM" -Name "myVMAccess" -Location "northeurope" -username <username> -password <password>
(7) You can connect to a VM in a scale set as by default the Load Balancer will have Nat Rules mapping from port onwards 50000, i.e. just remote desktop to the IP address:port. You can also do it from a VM that isn't in the scale set. Go to the scale set's overview, click on the "virtual network/subnet", that'll give you the internal IP address. Remote desktop from the other one
Ran into similar issues. It seems to need domain by default. Here is what worked for me:
localhost\username
Other option can be vmname\username
Some more guides to help:
https://learn.microsoft.com/en-us/azure/virtual-machines/windows/quick-create-portal#connect-to-virtual-machine
https://learn.microsoft.com/en-us/azure/virtual-machines/windows/connect-logon
In April 2022 "Password cannot contain the username or part of username" was the issue.
During the creation of VM in Azure, everything was alright but wasn't able to connect via RDP.
Same in Nov 2022, you will be allowed to create a password that contains the user name but during login it will display the credential error. Removing the user name from the password fixed it.

Expect: use output of remote command

I am new to using expect, and I've searched for an answer to the following question but haven't found it yet. I'm trying to log in to a server and run a command on that server. The command will output text including another command that I want to run and a password that I'll need.
E.g.
#!/usr/bin/expect --
<initialization of variables>
spawn ssh $user#$host
expect -re ".*sswor.*"
send "$password\r"
expect $prompt
send $command
expect magical stuff that I can use to create the next command
send $next_command
send $new_password
<more stuff>
The output of "send $command" above is
-bash-3.00$ <command from send>
Log into the next device by copying and pasting the following line: ssh new-user#new-host
The password to login is: Ex17dsk5
-bash-3.00$
Now what I need is to grab "ssh new-user#new-host" and "Ex17dsk5" and use them in $next_command and $new_password. I think I need to use expect_out(X,string) as I match expressions, but I haven't been able to figure out how to do it all.
Any help is greatly appreciated.
EDIT: ADDITIONAL INFORMATION AFTER RESPONSE BELOW
Thanks for the tip! However, it's still not working, but a lot closer. The code that I'm currently using is:
expect {
-re "Log into the remoteHost by copying and pasting the following line: ssh (.*)?\n?" {set remoteHostlogin "$expect_out(1,string)"; exp_continue}
-re "The password to login to the remoteHost is: (.*)\r\n" {set remoteHostpassword "$expect_out(1,string)"}
}
My thought was that the ? would make it non-greedy. However, it seems to be matching to the last \n in the buffer (see below). And since it matches to the last \n, expect_out(1,string) includes the password information that I'm trying to match with expect. The code produces the following debugging info:
You must ssh to the remoteHost from one of the log servers. Login to either Log Server 1 or Log Server 2 before logging into the remoteHost.
Log into the remoteHost by copying and pasting the following line: ssh 0005B9-cdmaremoteHost-0002F5007546#5.0.31.62
The password to login to the remoteHost is: B4dZsePI
expect: does "\r\nLast login: Tue Apr 3 14:32:48 2012 from log01i\r\r\nUse of CompanyName computing systems is restricted to authorized use only. \r\nThe use of any CompanyName computing system may be monitored and recorded \r\nby CompanyName for administrative and security reasons at any time. Your \r\nuse of these computing systems constitutes consent to this monitoring. \r\nCompanyName reserves the right to take appropriate action against anyone \r\nwho accesses or uses, or attempts to access or use, any CompanyName \r\ncomputing system improperly or without the appropriate authorization.\r\n\r\nYou have new mail.\r\n-bash-3.00$ ./get_remoteHost_login.sh 0002F5007546\r\n \r\n \r\nYou must ssh to the remoteHost from one of the log servers. Login to either Log Server 1 or Log Server 2 before logging into the remoteHost.\r\nLog into the remoteHost by copying and pasting the following line: ssh 0005B9-cdmaremoteHost-0002F5007546#5.0.31.62 \r\nThe password to login to the remoteHost is: B4dZsePI \r\n \r\n \r\n" (spawn_id exp6) match regular expression "Log into the remoteHost by copying and pasting the following line: ssh (.*)?\n?"? Gate "Log into the remoteHost by copying and pasting the following line: ssh *"? gate=yes re=yes
expect: set expect_out(0,string) "Log into the remoteHost by copying and pasting the following line: ssh 0005B9-cdmaremoteHost-0002F5007546#5.0.31.62 \r\nThe password to login to the remoteHost is: B4dZsePI \r\n \r\n \r\n"
expect: set expect_out(1,string) "0005B9-cdmaremoteHost-0002F5007546#5.0.31.62 \r\nThe password to login to the remoteHost is: B4dZsePI \r\n \r\n \r\n"
expect: set expect_out(spawn_id) "exp6"
expect: set expect_out(buffer) "\r\nLast login: Tue Apr 3 14:32:48 2012 from slog01i\r\r\nUse of CompanyName computing systems is restricted to authorized use only. \r\nThe use of any CompanyName computing system may be monitored and recorded \r\nby CompanyName for administrative and security reasons at any time. Your \r\nuse of these computing systems constitutes consent to this monitoring. \r\nCompanyName reserves the right to take appropriate action against anyone \r\nwho accesses or uses, or attempts to access or use, any CompanyName \r\ncomputing system improperly or without the appropriate authorization.\r\n\r\nYou have new mail.\r\n-bash-3.00$ ./get_remoteHost_login.sh 0002F5007546\r\n \r\n \r\nYou must ssh to the remoteHost from one of the log servers. Login to either Log Server 1 or Log Server 2 before logging into the remoteHost.\r\nLog into the remoteHost by copying and pasting the following line: ssh 0005B9-cdmaremoteHost-0002F5007546#5.0.31.62 \r\nThe password to login to the remoteHost is: B4dZsePI \r\n \r\n \r\n"
expect: continuing expect
EDIT
Thanks guys for you help! Below is what I finally settled on for my matching:
:
expect {
-re "Log into the remoteHost by copying and pasting the following line: (ssh .*\[0-9]+\.\[0-9]+\.\[0-9]+\.\[0-9]+)" {set remoteHostlogin "$expect_out(1,string)"; exp_continue}
-re "The password to login to the remoteHost is: (\[0-9a-zA-Z]{8})" {set remoteHostpassword "$expect_out(1,string)"}
}
Give this a shot. Also use exp_internal 1 in your script to enable internal diagnostics to troubleshoot.
expect -re "Log into the next device by copying and pasting the following line: (.*)\n" {
set loginstr "$expect_out(1,string)" }
expect -re "The password to login is: (.*)\n" {
set passwordstr "$expect_out(1,string)" }
send "$loginstr\r"
expect "*?assword*"
send "$passwordstr\r"