Menu
  • HOME
  • TAGS

test winrm connectivity on list of systems using powershell

Tag: powershell-v2.0,powershell-v3.0,powershell-remoting,winrm,wsman

I want to test whether or not winrm is running on a list of servers.

winrm id -r:servername works for individual systems but I want to test recursively for a list from a csv or text file.

With output to a file saying "working" or "not working" for each.

How do I do this?

Thanks all.

Edit:
Gotten to a point where I am passing a list of vm's and piping along until I get successful winrm connections output to a file and failures shown in the console.

get-vm |where {$.powerstate -like "PoweredOn"}|get-vmguest |where {$.guestfamily -like "windowsGuest"}|foreach {winrm id -r:$_.hostname} |Out-File c:\scripts\winrmtest.txt

In my out-file I am getting output like IdentifyResponse ProtocolVersion = http://schemas.dmtf.org/wbem/wsman/1/wsman.xsd ProductVendor = Microsoft Corporation ProductVersion = OS: 6.1.7601 SP: 1.0 Stack: 2.0

for successful connections and on the console I get the following for failures:

Error number: -2144108526 0x80338012 The client cannot connect to the destination specified in the request. Verify that the service on the destination is run ning and is accepting requests. Consult the logs and documentation for the WS-Management service running on the destinat ion, most commonly IIS or WinRM. If the destination is the WinRM service, run the following command on the destination t o analyze and configure the WinRM service: "winrm quickconfig". WSManFault Message = The client cannot connect to the destination specified in the request. Verify that the service on the dest ination is running and is accepting requests. Consult the logs and documentation for the WS-Management service running o n the destination, most commonly IIS or WinRM. If the destination is the WinRM service, run the following command on the destination to analyze and configure the WinRM service: "winrm quickconfig".

Need to get all the output into the file, along with the name of the guest vm the response is for.

Best How To :

Please keep in mind I have not used the VM cmdlets, however below is some code I think should help you. I added a wmi to check the winrm service on each machine, if the service isn't running, look at the startservice() method for the win32_service. if this is unfamiliar to you, pipe | gm to see available properties and methods.

However here are a few recommendations:

  • PowerShell Objects

Exporting and managing data is easy and clean.

  • "-Filter" vs "Where{}"

    Look into the VM cmdlets and see if they support -filter {property -operator "*filterby*"} your code will run much faster.

$All_VMS_Status = @()

get-vm | where {$.powerstate -like "PoweredOn"} | get-vmguest | where {$.guestfamily -like "windowsGuest"} | foreach {

<# Create PowerShell Object with Hostname #>
$psobject = New-Object -TypeName psobject
$psobject | Add-Member -MemberType NoteProperty -Name "VM-HostName" -Value $($_.HostName)

<# Determin if WINRM is working #>
if(winrm id -r:$_.hostname) {
    $Connection_Status = "Success"
} Else {
    $Connection_Status = "Failed"
}

<# Check winrm service on remorte PC #> 
$remote_winrm_Service = Get-WmiObject win32_service -ComputerName $($_.hostname) | Where{ $_.Name -eq "winrm"}

<# Add all information to PS object for exporting #>    
$psobject | Add-Member -MemberType NoteProperty -Name "Winrm-Connection" -Value $Connection_Status
$psobject | Add-Member -MemberType NoteProperty -Name "winrm-state" -Value $($remote_winrm_Service.State)
$psobject | Add-Member -MemberType NoteProperty -Name "winrm-startmode" -Value $($remote_winrm_Service.StartMode)
$psobject | Add-Member -MemberType NoteProperty -Name "winrm-ExitCode" -Value $($remote_winrm_Service.ExitCode)
$psobject | Add-Member -MemberType NoteProperty -Name "winrm-Status" -Value $($remote_winrm_Service.Status)

$All_VMS_Status += $psobject

}

<# Export to csv #>
$All_VMS_Status | Export-Csv -Path "c:\scripts\winrmtest.csv" -NoTypeInformation`

Processing a list with Powershell on a Scheduled Task

powershell,powershell-v2.0

Assuming you have a string array that was populated with Get-Content and assuming the array did not contain duplicates, you could use the Array.IndexOf method to get the index of the current id and then return the next element in the array. Example: $x = "1","2","3" $currentId = "2" $nextIndex...

Remove numerous characters including underscore

powershell-v2.0

$pattern = '(.*)_\d{6}(.csv)' Get-ChildItem -Recurse | ? { $_.Name -match $pattern } | Rename-Item -NewName { $_.Name -replace $pattern, '$1$2' } ...

Where can i find PowerShell cmdlet to Object Class documentation?

.net,powershell,powershell-v2.0

You'd have to find out the underlying dotnet method that's used to do the work and look a its documentation. In case of your example probably the CreateDirectory method: Exception Condition IOException The directory specified by path is a file. -or- The network name is not known. UnauthorizedAccessException The caller...

Copying folder contents from one server to another using Windows PowerShell scripting

powershell-v3.0

Got the following snippet which maintains the sub-folder structure: $sourceDir="\Server1\SourceFolder\" $targetDir="\Server2\DestinationFolder\" Get-ChildItem $sourceDir -Recurse | % { $dest = $targetDir + $_.FullName.SubString($sourceDir.Length) If (!($dest.Contains('.')) -and !(Test-Path $dest)) { mkdir $dest } Copy-Item $_.FullName -Destination $dest -Force }...

Unexpected token error when I have the variable already defined

powershell,powershell-v2.0

The error is trying to tell you it does know what to do with $ip. It does not care at this point whether it is a variable or not. It's a parsing error. $computer + ";" $ip should instead be the following ( in keeping with your coding practice.) $computer...

exlude folder with specific extensions after recursively search

powershell,powershell-v2.0

This returns directories containing list of extensions that do not contain avi: gci -Recurse -include *.mp3 , *m3u, *.jpg | ? { !(gci "$($_.Directory)\*.avi") } This will be much faster if you cache internal loop gci results for a directory....

How to get the tfs build folder name, generated inside dropfolder while running the TFS build

tfsbuild,powershell-v3.0,tfs2013

For completeness please see the answer: $ENV:TF_BUILD_DROPLOCATION Using the above Team Foundation Build environment variable gives the output as \\server-name\TFSBuildOutput\TFSBuildOutput_20150609.2 Example - \\USTR-ERL-4608\Build Output\TBR Daily Build\TBR Daily Build_20150609.2...

How to rename the most recent files in order?

powershell-v3.0

This seems to handle the problem, but I want to run more tests, to be certain, @justinf What I wanted was to rename files - like so: ParentFolder_000 - and keep them in order by the date I created the file. So...here you can see I have a bunch of...

Format a command in powershell including a comma, can't find the right way to escape

powershell,batch-file,escaping,powershell-v2.0,comma

".\pacli DELETEUSER DESTUSER='"[email protected]`,com"' sessionid=333" You have double quotes in single quotes in double quotes, so the inner double quotes will terminate the string, so this will be parsed as three values: ".\pacli DELETEUSER DESTUSER='" [email protected]`,com "' sessionid=333" The answer is to escape, with a back tick (`), the inner...

Update SharePoint list entry using ListData.svc and PowerShell

powershell,sharepoint,sharepoint-2010,odata,powershell-v3.0

The following example demonstrates how to update List Item using SharePoint REST Interface: <# .Synopsis Update Lst Item .DESCRIPTION Updates List Item operation using SharePoint 2010 REST Interface. To update an existing entity, you must perform the following actions: - Create an HTTP request using the POST verb. - Add...

How to select multi-line strings (including spaces), return true if found - PowerShell/SQL Batch

sql-server,powershell,batch-file,powershell-v2.0,powershell-v3.0

You can use regex with the multiline option: $a = @' Return Value ------------ 0 '@ $b = @' Return Value ------------ 1 '@ [regex]::Match($a, 'Return Value\s*------------\s*0', [System.Text.RegularExpressions.RegexOptions]::Multiline).Success # true [regex]::Match($b, 'Return Value\s*------------\s*0', [System.Text.RegularExpressions.RegexOptions]::Multiline).Success # false If you post an exmpale of your log, I can adapt the script more...

Implement the subcommand pattern in PowerShell

powershell,powershell-v3.0

I thought of this pattern and found two ways of doing this. I did not find real applications in my practice, so the research is rather academic. But the scripts below work fine. An existing tool which implements this pattern (in its own way) is scoop. The pattern subcommand implements...

Run Exchange Powershell commands from Linux using Ruby/WinRM

ruby,powershell-v2.0,winrm,exchange-management-shell

We managed to get it to work. I had to first connect to a 'management' server to initiate the powershell command. endpoint = 'http://YOURSERVER:5985/wsman' krb5_realm = 'YOURREALM' winrm = WinRM::WinRMWebService.new(endpoint, :kerberos, :realm => krb5_realm) Then I had to modify the exchange command to this: exch_cmd = "Enable-Mailbox -Identity:'DOMAIN/OU/#{fullname}' -Alias:'#{username}' -Database:'#{MailboxDB}'"...

Merge Text Files and Prepend Filename and Line Number - Powershell

powershell,text,powershell-v3.0

Not beautiful but this is one approach. Get-ChildItem *.txt | %{$FILENAME=$_.BaseName;$COUNT=1;get-content $_ | %{"$FILENAME"+"$COUNT"+" " + "$_";$COUNT++}}| Out-File Output.txt ...

call custom functions from Add-ons menu in Powershell ISE

powershell,menu,powershell-v3.0,powershell-ise

$CommandList = Get-Command -Module "CompanyModules" | Select-Object Name -ExpandProperty Name What you've done here is you've only gotten the name of each function in $CommandList. So instead let's change it to this: $CommandList = Get-Command -Module "CompanyModules" to get the entire command object. Then at the bottom of the script:...

Sort an PowerShell array according to a part of content in each element

arrays,sorting,powershell,powershell-v2.0,powershell-v3.0

If you want to sort by date and time, this is one way of doing it. This is your data as an array $data = @("201410212339/21-Oct-2014 23:50 -", "2251/27-Sep-2014 23:02 -", "0436/22-Oct-2014 04:47 -", "091342/09-Oct-2014 13:53 -", "2220743/22-Oct-2014 07:53 -", "20140/22-Sep-2014 07:41 -", "2190446/19-Oct-2014 04:56 -", "2014258/21-Aug-2014 23:21 -", "22110/22-Oct-2014...

Powershell Proxy setting

powershell,proxy,powershell-v2.0

Enter-PsSession -Computername "nameofcomputer" | Get-ItemProperty Registry::HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings' | Select-Object *Proxy* This however requires the WinRM service to be running on the target host. If WinRM is not running it could be ran as a logon script with | Out-file "someplace\output.txt" then share that folder to get the data. ...

Custom Powershell Host Invoke external program without console window

c#,visual-studio,powershell,powershell-v2.0

It turns out that this is expected behavior of invoking console commands. In Windows 7 and above conhost.exe is responsible for handling calls to console programs. In this case, ping and netstat trigger an instance of conhost to be created, it handles the request, returns the results, and then remains...

Display element's attribute using PowerShell's Format-Table

powershell,sharepoint,sharepoint-2010,powershell-v3.0

you dont have to use a hashtag. PS>$xml.feed.entry.content.type application/vnd.openxmlformats-officedocument.spreadsheetml.sheet ...

Create powershell parameter default value is current directory

powershell,powershell-v3.0

Use PSDefaultValue attribute to define custom description for default value. Use SupportsWildcards attribute to mark parameter as Accept wildcard characters?. <# .SYNOPSIS Does something with paths supplied via pipeline. .PARAMETER Path Specifies a path to one or more locations. Wildcards are permitted. The default location is the current directory (.)....

How to set file type for files without any type

powershell,powershell-v2.0

If you want to set the extension of all the files in a folder without an extension to .srt you can use Rename-Item from the pipeline like this Please be careful, this will change the extension of ALL files without an extension in the directory you choose to .srt Get-ChildItem...

Powershell v2 and PowerShell v3 Object handling

powershell,powershell-v2.0,powershell-v3.0

This is actually because you are wrapping the object in an array. In v2, to get all of the Action properties of an array of objects, you would do something like this: $Services | ForEach-Object { $_.Action } # or $Services | Select-Object -ExpandProperty Action In PowerShell v3, this is...

Exporting Drive Letters to Columns

powershell,server,powershell-v3.0

Unless there is more to this code the simple answer appears to be just use -join in conjunction with something like Add-Content to set the line. Obviously you have this in some sort of loop structure which should not be affected here. $results = Get-WmiObject win32_logicaldisk -filter "drivetype = '3'"...

Color a cell on the basis of another cell value

html,powershell,powershell-v2.0

You should format your HTML result with a different style if there's a condition. To do that, you declare a variable for data style that should be equal to $normalDataStyle if your condition is false, and a special style if it's true. $redDataStyle='style = "border: 1px solid black; background: #c00000;...

Retrieving session ID from COM method

powershell,com,powershell-v3.0

PowerShell seems to have a problem with COM parameters defined as VARIANT. This is the case here, as the C++ signature of GoLogon suggests. STDMETHODIMP CLOG::GOLogon(VARIANT *pvEmailId, BSTR bsPassword, BSTR bsIPAddress, BSTR bsSoloBuildVer, VARIANT *pvXML, BSTR *bsSessionId) The answer suggested in this post "Invalid callee" calling a com object is...

Replace NTFS Permissions with PowerShell

permissions,powershell-v3.0,ntfs

I guess this question rather belongs to Server Fault, but I'd use ADMT (Active Directory Migration Tool, https://technet.microsoft.com/en-us/library/cc974332%28v=ws.10%29.aspx).

Renaming files with similar pattern

powershell,powershell-v2.0

Assuming that all subtitle files begin with the basename of their respective video file something like this should work: Get-ChildItem '*.mkv' | % { $newname = Get-Item ($_.BaseName + '*.srt') | select -First 1 -Expand BaseName if ($newname) { Rename-Item $_ "$newname.mkv" } } select is an alias for Select-Object,...

start-process with a special name, or handle to kill it

powershell,powershell-v3.0

One method is to use the -PassThru parameter, which causes Start-Process to return an object which can be used to control the process. When you're done with the process, pipe the object to Stop-Process (or call the object's Kill() method) In cases where you need to store the object across...

Access SharePoint expanded properties

powershell,sharepoint,sharepoint-2010,odata,powershell-v3.0

The query is malformed since $ symbol have to be escaped using single-quoted string literals, for example: $url = "http://contoso.intranet.com/_vti_bin/listdata.svc/TheList?`$select=Id,Title,Stakeholder/Name&`$expand=Stakeholder" Then Stakeholder value could retrieved as demonstrated below: $StakeholderValue = $data.link | where { $_.title -eq "Stakeholder" } | select -Property @{name="Name";expression={$($_.inline.entry.content.properties.Name)}} Modified example $url =...

powershell error recovery from native applications

powershell,powershell-v3.0

You can use one of the two automatic variables that indicate the last exit code: $LASTEXITCODE and $? If the schtasks /query succeeds, $LASTEXITCODE will be 0 and $? will be $true On the other hand, if the schtasks /query call fails, $LASTEXITCODE will contain a non-0 exit code and...

Improve code to use optional switch parameter in PowerShell

powershell,powershell-v3.0

Yes, you can pass a boolean to a switch parameter. In your case: -Verbose:$verbose example: function DoSomething { [CmdletBinding()] Param() Write-Verbose "output" } DoSomething -verbose:$true # Does write output DoSomething -verbose:$false # no output ...

Load script from PowerShell ISE's command environment

powershell,powershell-v3.0,powershell-ise

Instead of Invoke-Item, just use ise. When run from the ISE, it will load the file. PS> ise myscript.ps1 To make Invoke-Item behave like you want (as well as double-clicking from Explorer), you can associate .ps1 files with powershell_ise.exe. Here is a blog post explaining how to do this if...

Simultaneous PowerShell script execution

powershell-v2.0

Thanks Ansgar Wiechers. This piece of code did it. It helps in executing the .exe simultaneously on all the servers as well as track their status: cls $servers = Get-Content 'D:\Abhi\Server.txt' $servers | ForEach-Object {$comp = $_ Start-Job -ScriptBlock {psexec \\$input -s -u Adminuser -p AdminPassword C:\SQL_PATCH\SQLServer2008R2SP3-KB2979597-x64-ENU.exe /quiet /action=patch /allinstances...

Upload file to SharePoint 2010 using PowerShell and the OData API

powershell,sharepoint,sharepoint-2010,odata,powershell-v3.0

In order to create an attachment resource the following properties have to be specified: Endpoint Uri: http://server/site/_vti_bin/listdata.svc/entityset(itemid)/Attachments Method: POST Headers: Slug: "entityset|itemid|name" ContentType: */* Body: content Having said that, my conslution that the specified body parameter ($payload) is invalid in the provided example. The following example demonstrates how to upload...

Prevent coercion

powershell,powershell-v3.0

No, unfortunately not. From the about_Parsing help file: When processing a command, the Windows PowerShell parser operates in expression mode or in argument mode: - In expression mode, character string values must be contained in quotation marks. Numbers not enclosed in quotation marks are treated as numerical values (rather than...

Powershell function with two argument give takes one argument [duplicate]

function,powershell,powershell-v2.0

Kayasax has answered the question in his comment. Function calls do not require parens around the argument(s). call with t 4 5 instead of what you did....

More-efficient way to modify a CSV file's content

powershell,csv,powershell-v3.0,ssms-2012

Import-CSV always loads entire file in memory, so it's slow. Here is modified script from my answer to this question: CSV formatting - strip qualifier from specific fields. It uses raw file processing, so it should be significantly faster. NULLs and milliseconds are matched\replaced using regex. Script is able to...

How to read and parse from multiple files?

powershell,powershell-v3.0

Assuming that this is your $raw output: string1=1 string2=8 string3=2015-06-02 23:58:11 string1=1 string2=8 string3=2015-06-02 23:58:11 string1=1 string2=8 string3=2015-06-02 23:58:11 and you want this as the result: string1=1 string2=8 string3=2015-06-02 23:58:11 string1=1 string2=8 string3=2015-06-02 23:58:11 string1=1 string2=8 string3=2015-06-02 23:58:11 you could do something like this: $raw = Get-Content "C:\folderpath\*.*" $raw =...

Enhancing the pipeline's content?

powershell,powershell-v3.0

Updating archive .\files.zip ... Compressing files.zip ? Check if your function has a case when adding Archive.zip to Archive.zip, this should throw a warning like copying over itself. About pipeline - I think you should employ -passthru switch, if the switch is present, return the archive as a Get-Item result...

PowerShell + AD: Return users from within any groups in a specific OU, plus count

active-directory,powershell-v3.0,quest

You can pretty easily simplify this: $Users = Get-ADGroup -SearchBase 'ou=XXX,ou=XXX,dc=XXX,dc=XXX,dc=org' -Filter * ` | Get-ADGroupMember -Recursive ` | Select-Object -Unique ` | Sort-Object DistinguishedName; $Users | Select-Object Name, DistinguishedName; Write-Output ("Total Users = {0}" -f $Users.Count); If you want to search by group name, you can change the first...

Moving every n files into a separate folder

powershell,powershell-v2.0

This could be done with a simple Switch. The switch will be run against all items in the current folder (items gotten with the Get-ChildItem cmdlet which you use by it's alias 'LS'). It looks to see if the file has the string "Intro" in the file name. If it...

Excessive whitespace around filepath

powershell-v2.0

The Format-* cmdlets are for displaying formatted data to the user. Do not use them if you need to further process your data. Simply expand the FilePath property instead: $outlook.Session.Stores | where { $_.FilePath -like '*.PST' } | select -Expand FilePath...

PowerShell Iterate through array and if match copy-item

powershell-v3.0

I've updated after seeing the format of your file and the expected file names. The first line skips the first two lines of 2cHotfix.txt as we don't want to try and match "Hotfixid" or a blank line. We then check to see if we have any files in the current...

Convert Hashtable Values In-Place

string,powershell,hashtable,powershell-v2.0

I don't think there's a "more efficient" way of changing the values. You can set the values of each key to a value of a new type ($hash[$key] = $hash[$key].ToString()) but this is complicated if you're looping because you're changing the object being enumerated. You can get around this in...

ACL “fuzzy” comparision

arrays,powershell,comparison,powershell-v2.0

I'd do something like this: $defaults = 'BUILTIN\Administrators', 'MYDOMAIN\DomainGroup', 'S-1-5-21*' $access | ? { $id = $_.IdentityReference -not ($defaults | ? { $_ -like $id }) } | select -Expand value $defaults | ? { $_ -like $id } does a wildcard match of the given identity against all items...

Distinguish Windows services with the same ProcessName

powershell,memory,windows-services,monitoring,powershell-v3.0

You say that the path to executable is different - this way you can distinguish the processes by querying path property. Should they be equal, you can also query StartInfo object of a process to get Arguments property to discern from one another. But the best way to get correct...

Bind every line from two variables in a third variable in powershell

variables,powershell,powershell-v2.0

this is a rapid way (variables's lenght must be equal): $i = 0 ; $var3 = $var1 | % { "$_ $($var2[$i])"; $i++ } ...