Improve PS Scripts (jobs, ping, etc) - powershell

I've prepared a script in PS, which part looks like this:
"$Octets.11","$Octets.12","$Octets.13","$Octets.14",..., "$Octets.51" - I'd like to 'cut' this part of code, is it possible to write sentence like: "$Octets.11" - "$Octets.51" ?
My script was written to ping some devices in LAN. When some computers are active, the script shows them together at once as ACTIVE, but when it's not, it's pinging for 3 seconds and then shows its inactive, then starts ping another (inactive) and go on. It takes a lot of time to wait dor result. Can I create a function/job to ping every device at once?
Thank you for every hint!

Using test-connection -asjob (unfortunately the headers don't match the properties):
# 1..60 | % tostring 1\0\.\0\.\0\.0
test-connection (1..60 | % tostring comp000) -AsJob -count 1 |
receive-job -wait -auto # 5 seconds
Source Destination IPV4Address IPV6Address Bytes Time(ms)
------ ----------- ----------- ----------- ----- --------
MYCOMP comp001 10.0.0.1 32 3
MYCOMP comp002 10.0.0.2 32
MYCOMP comp003 10.0.0.3 32 2
(null responsetime is down)
(address is the hostname)
This doesn't seem to use any extra processes.

Related

Why is Get-DnsClientServerAddress | select AddressFamily output not IPv4 and IPv6

When I type the cmdlet Get-DnsClientServerAddress I get all the interfaces my PC has like for example
InterfaceAlias Interface Address ServerAddresses
Index Family
-------------- --------- ------- ---------------
Ethernet 7 IPv4 {10.10.15.40, 10.10.25.44}
So when I type in Get-DnsClientServerAddress | where AddressFamily -Like "4" I would expect to see the Ethernet Adapter.
But for any reason it didn't show up. So I typed Get-DnsClientServerAddress | select AddressFamily and what I got was
AddressFamily
-------------
2
23
2
23
Can anyone explain this to me ?
As you found, the AddressFamily is categorised internally using a (not obvious) numbering scheme, where IPv4 addresses are type '2'. This comes from the underlying WMI type (MSFT_DNSClientServerAddress) and is not an issue with PowerShell.
The default display helps you out by translating this to IPv4, etc, but you can't filter on that as it's for display only. You can, however, still filter if you use the correct value:
Get-DnsClientServerAddress | Where-Object AddressFamily -Like 2
This formatting of data for display purposes happens all the time in PowerShell and is acheived through Format.ps1xml files. For example, compare the output of the Working Set values from Get-Process in table and list format:
PS C:\> Get-Process powershell
Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName
------- ------ ----- ----- ------ -- -- -----------
662 31 97928 110256 1.27 11452 2 powershell
PS C:\> Get-Process powershell | Format-List *
Handles : 705
VM : 2204040044544
WS : 113082368
PM : 100356096
NPM : 31512
The property (itself added by PowerShell for convenience) is called WS, but is shown as WS(K) in the table and the actual value is stored in bytes, but is displayed in KB, so some manipulation is going on for the default output.
Following from my comment, I would use Get-NetIPAddress instead.
Get-NetIPAddress -InterfaceAlias "Ethernet" | Select-Object FamilyAddress

VMWare PowerCLI Get DiskUsage of powered off vm's

I'm creating a script that gets all vm's and shows the DiskSpace. THe Problem is, that if a vm is powered off, it won't show the uesed Space of a disk.
Here are two examples: First one with an VM that is powered on:
PowerCLI C:\> Get-VM sluwv0039
Name PowerState Num CPUs MemoryGB
---- ---------- -------- --------
sluwv0039 PoweredOn 2 4.000
PowerCLI C:\> $VM = Get-VM sluwv0039
PowerCLI C:\> $VM.guest.disks
CapacityGB FreeSpaceGB Path
---------- ----------- ----
49.997 5.417 C:\
Example two where the VM is powered off:
PowerCLI C:\> Get-VM sluwv0012
Name PowerState Num CPUs MemoryGB
---- ---------- -------- --------
sluwv0012 PoweredOff 4 8.000
PowerCLI C:\> $VM = Get-VM sluwv0012
PowerCLI C:\> $VM.guest.disks
PowerCLI C:\>
Note: The Last line is the output. There is no "CapacityGB" etc.
Correct, that property is reading from the guest file system to see how much space is left on the partition. In your case, the C:\ drive. If the VM is off, there's no way for PowerCLI to find that property.
Alternatively, you could look at the $vm.ExtensionData.Summary.Storage properties and do some rough conversions. Note: the output of those are in byte, so you'll want to convert them to GB. Example: $tempVM.ExtensionData.Summary.Storage.Committed / 1GB
It won't be exact, but it will be better than no output at all.
here is example of script to show vm specification:
Get-Vm | Select-Object Name,PowerState,VMHost,NumCPU,MemoryGB,ProvisionedSpaceGB,#{N="HostName";E={#($.guest.HostName)}},#{N="Gateway";E={#($.ExtensionData.Guest.IpStack.IpRouteConfig.IpRoute.Gateway.IpAddress[0])}},#{N="DNS";E={$.ExtensionData.Guest.IpStack.DnsConfig.IpAddress}},#{N="IPAddress";E={#($.guest.IPAddress -like "192.168.*")}},#{N="Nics";E={#($.guest.Nics)}},#{N="Datastore";E={#($ | Get-DataStore)}},#{N="Disks";E={#($.guest.Disks)}},Version,#{N="State";E={#($.guest.State)}},#{N="OS";E={#($_.guest.OSFullName)}}
the sample output is like this:
Name State VMHost NumCpu MemoryGB PowerState ProvisionedSpaceGB Version IPAddress HostName OS Nics Disks VMwareTools Gateway DNS
test Running 192.168.32.100 2 1 PoweredOn 43.1085147 v8 192.168.122.1 Elenoon Ubuntu Linux (64-bit) Network adapter 1:VM Network Network adapter 2:local : : Capacity:17167286272, FreeSpace:14212493312, Path:/ Capacity:15188623360, FreeSpace:15154872320, Path:/media/files Capacity:10724835328, FreeSpace:10672824320, Path:/var/log Capacity:973770752, FreeSpace:690139136, Path:/boot guestToolsRunning 127.0.0.1
hope to be useful ;)

qwinsta /server:somesrv equivalent in Powershell?

When I run the qwinsta /server:somesrv command in cmd I can get a listing of all the current RDP sessions that are logged into a particular Windows server.
SESSIONNAME USERNAME ID STATE TYPE DEVICE
console 0 Conn wdcon
rdp-tcp 65536 Listen rdpwd
rdp-tcp#594 tom1 1 Active rdpwd
rdp-tcp#595 bob1 2 Active rdpwd
Is it possible to get a list like this on a remote server from Powershell so that the data can be used elsewhere?
There are multiple alternatives:
Use the Terminal Services PowerShell Module. Easy solution.
Writing a powershell wrapper that parses the output of qwinsta to objects. Easy solution. See example below
Use the Cassia.DLL .Net wrapper to access the native APIs that qwinsta runs behind the scene. This is the class that the TS Module uses. More difficult, but will have the benefit of being customized to your needs.
Go crazy and use the Native Methods that Cassia.DLL accesses using P/Invoke (wtsapi32.dll, kernel32.dll, winsta.dll). Hard and overcomplicated.
PowerShell-wrapper for qwinsta
function Get-TSSessions {
param(
$ComputerName = "localhost"
)
qwinsta /server:$ComputerName |
#Parse output
ForEach-Object {
$_.Trim() -replace "\s+",","
} |
#Convert to objects
ConvertFrom-Csv
}
Get-TSSessions -ComputerName "localhost" | ft -AutoSize
SESSIONNAME USERNAME ID STATE TYPE DEVICE
----------- -------- -- ----- ---- ------
services 0 Disc
console Frode 1 Active
rdp-tcp 65537 Listen
#This is objects, so we can manipulate the results to get the info we want. Active sessions only:
Get-TSSessions -ComputerName "localhost" | ? { $_.State -eq 'Active' } | ft -AutoSize SessionName, UserName, ID
SESSIONNAME USERNAME ID
----------- -------- --
console Frode 1
I used to use Terminal Services PowerShell Module (now in codeplex archive), but it was two years ago. I can't put my hand on it, but it also exists a function on gitshub or another site that embeded QWinsta/RmWinsta.

PowerShell: Getting Help on Get-Process -Property CPU

With PowerShell 3, I tried to get help on what properties are available for CPU; while using Get-Process. I just tried a shot in the dark, as below:
Help Get-Process -Property CPU
But, failed. Any help, please!
What are you looking for? Information about your processor? Get-Process list running processes(e.g. internet explorer) on your computer, not info about your processor-chips(CPU). Ex:
Get-Process
Output:
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
------- ------ ----- ----- ----- ------ -- -----------
284 25 7128 8748 103 1608 AppleMobileDeviceService
75 7 1136 1528 44 1588 armsvc
703 82 6612 7732 114 1,25 4212 AsusAudioCenter
Information about your processor can be found using:
Get-WmiObject Win32_Processor
Output:
Caption : Intel64 Family 6 Model 42 Stepping 7
DeviceID : CPU0
Manufacturer : GenuineIntel
MaxClockSpeed : 3400
Name : Intel(R) Core(TM) i7-2600 CPU # 3.40GHz
SocketDesignation : LGA1155
To get all properties about your CPU use Get-WmiObject Win32_Processor | fl *. To get a list of avaiable properties, use the Get-Member cmdlet to examine the object that Get-WmiObjectreturns:
Get-WmiObject Win32_Processor | Get-Member
Your shot in the dark missed. Also, since your description of what went wrong is nothing more than "But, failed.", I can only guess at what your problem might be. In order to better help you use help you need to help us by providing pertinent information about your problem such as error messages.
Firstly, Help (or the Get-Help cmdlet) does not have a -Property parameter. -Parameter might be what you looking for, however running Help Get-Process -Parameter CPU will reveal that the Get-Process cmdlet does not have a CPU parameter.
Secondly, Get-Process returns instances of the System.Diagnostics.Process class. The documentation or running Get-Process | Get-Member will show you what properties that class exposes. You can retrieve them by running something like...
Get-Process | Select-Object -Property (
'ProcessName',
'Id',
'ProcessorAffinity',
'UserProcessorTime',
'PrivilegedProcessorTime',
'TotalProcessorTime'
);
Finally, unlike previous versions PowerShell 3.0 does not install local help content. You need to run the Update-Help cmdlet to download and install help content. Alternatively, when running Get-Help you can pass the -Online parameter which will open the help content from MSDN in a web browser.

Powershell Test-Connection: different results when run AsJob vs straight-up

Short version: Why does Test-Connection provide only one result when running -AsJob?
Detailed version:
When the Test-Connection (ping!) command is run in Powershell (running as Administrator) it uses the default value of 4 for the Count parameter. This gives me the expected results (some irrelevant data removed for clarity):
PS C:\Windows\system32> Test-Connection www.stackoverflow.com
Destination IPV4Address IPV6Address Bytes Time(ms)
----------- ----------- ----------- ----- --------
www.stackove... 64.34.119.12 {} 32 117
www.stackove... 64.34.119.12 {} 32 113
www.stackove... 64.34.119.12 {} 32 111
www.stackove... 64.34.119.12 {} 32 113
However, when I run it with the -AsJob flag, it seems (when running Receive-Job, after waiting a few secs) the Count was only 1, but I expected it to be 4 and get similar results as above. Instead I get this:
PS C:\Windows\system32> Test-Connection www.stackoverflow.com -AsJob
Id Name State HasMoreData Location Command
-- ---- ----- ----------- -------- -------
1 Job1 Running False . Test-Connection
PS C:\Windows\system32> Receive-Job 1
Destination IPV4Address IPV6Address Bytes Time(ms)
----------- ----------- ----------- ----- --------
www.stackove... 64.34.119.12 {} 32 113
The AsJob variant always returns one row, even if you provide a specific value for Count.
My Google-fu and Get-Help-fu don't seem to be sufficient. Can someone please explain what's going on here, preferably with some pointers how and where to find this info myself (e.g. which help files or sources explain this behavior)?
Could be a bug. In v3 you get back 4 pings.