Powershell list with IPAddress, Prefixlength and Computernames - powershell

I've write a PS Script, that gives me all IP Addresses and Prefixlength of Servers from a text file. See code:
$cred = Get-Credential
$computers = Get-Content -Path C:\Users\XX_YY\Desktop\test_hostname_file.txt
invoke-command -computername $computers -Credential $cred -scriptblock {get-netipaddress -AddressFamily IPv4 } | where {$_.ipaddress -like "10.*"} | ft -AutoSize IPaddress, prefixlength
This Script gives me the result as a table. But I need the Computernames as well in the table.
have you an idea how I can handle this?
Cheers Sam

Well, I would do it in another way, but to stick to your question:
You can use the Automatic variable $ENV:ComputerName to get the computer name and add it to the output using a PS Object
$cred = Get-Credential
$computers = Get-Content -Path C:\Users\XX_YY\Desktop\test_hostname_file.txt
invoke-command -computername $computers -Credential $cred -scriptblock {
$IP = get-netipaddress -AddressFamily IPv4 | where {$_.ipaddress -like "10.*"}
$Row = "" | Select Computer,IPaddress,prefixlength
$Row.Computer = $env:COMPUTERNAME
$Row.IPaddress = $IP.IPaddress
$Row.prefixlength = $IP.prefixlength
return $row
}

Related

Using Powershell Get-ItemProperty through all of AD computers object

I'm a complete newbie in Powershell (and programming as you may have guessed), I want to get the result of the following PS command for each of our AD computer object and print the result in a text file...but I'm completely lost. Does anyone have a lifeline I could hold on to?
Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" | Select-String -Pattern "mysoftwarename"
Thank you very much.
$ScriptBlock = {Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" | Select-String -Pattern "mysoftwarename"}
$Computers = (Get-ADComputers -filter * ).name
$Creds = (Get-Credential)
foreach ($Computer in $Computers)
{
"`n`n$Computer`n" >> .\file.txt # "`n" just emulates Enter key press
Invoke-Command -ComputerName $Computer -ScriptBlock $ScriptBlock -Credential $Creds >> .\file.txt
}
This will work fine if you have all your computers online and PS remoting configured properly. Otherwise, it will require modifications.

Formating List Problems in Powershell

I want to execute a few lines of code on every Server (160+).
For this I decided to get my Serverlist via Powercli and pass this list to Enter-PSSession.
...
Connect-VIServer -Server $VIServer -Credential $creds
$servers = Get-VM |select Name |where Name -Like "SV*"
...
foreach($server in $servers)
{
try{
Enter-PSSession -ComputerName $server -Credential $cred -ErrorAction Stop
Get-NetIPAddress |where AddressFamily -EQ 2 |where InterfaceAlias -Like "Ethernet" |select IPAddress
Exit-PSSession
}catch{
Write-Host "Error on $server"
}
}
the problem seems to be, that it takes an array as the ouput error is following
Error on #{Name=<$server>}
But I dont know how to handle this correctly
Use New-Pssession or Invoke-command for remoting. Enter-Pssession is interactive and the way you are doing it, the get-netipaddress is running on your local machine and not on your remote machine.
Use $servers.Name instead of $servers in your foreach loop.
foreach($server in $servers.Name) #This .name should fix your problem
{
try{
New-PSSession -ComputerName $server -Credential $cred -ErrorAction Stop -Name MySession
Invoke-Command -Session $MySession -ScriptBlock {Get-NetIPAddress |where AddressFamily -EQ 2 |where InterfaceAlias -Like "Ethernet" |select IPAddress}
Remove-PSSession
}catch{
Write-Host "Error on $server"
}
}

Upgraded output for powershell script

I am trying to write script that will check servers hostnames.
Now I have:
Computers.txt
192.168.10.10
192.168.10.11
192.168.10.12
and script:
$servers = get-content "C:\Script\computers.txt"
Invoke-Command -Credential company\admin1 -ComputerName $computers -scriptblock {[Environment]::GetEnvironmentVariable("ComputerName")} | out-file C:\Script\report_hostnames.txt
And I have report:
Computer1
Computer2
Computer3
Could you help me add IP adress to report, and error status, like this:
192.168.10.10 Computer1
192.168.10.11 Computer1
192.168.10.12 Computer Unavailable
I tried: foreach; try, catch and if, else but cannot understand how to use it in right way.
Try this:
get-content "C:\Script\computers.txt" | foreach {
$Response = Invoke-Command -Credential company\admin1 -ComputerName $_ -scriptblock {[Environment]::GetEnvironmentVariable("ComputerName")}
write-output "$_ $Response" | out-file C:\Script\report_hostnames.txt
}
Using an array inside the -ComputerName attribute and then piping the output forward to out-file doesn't give you a way to access the contents of -ComputerName attribute (at least that I know of). Breaking it up into a basic foreach does.
You should be able to use DNS to look up the host names. Example:
Get-Content "IPAddresses.txt" | ForEach-Object {
$outputObject = [PSCustomObject] #{
"IPAddress" = $_
"HostName" = $null
}
try {
$outputObject.HostName = [Net.Dns]::GetHostEntry($_).HostName
}
catch [Management.Automation.MethodInvocationException] {
$outputObject.HostName = $_.Exception.InnerException.Message
}
$outputObject
}

Retrieve software that has been authorized to pass through firewall in powershell

The code below turns off firewall on each remote computers and return any computers that was turned off. I am also trying to retrieve software that has been authorized to pass through firewall for each computer.
I understand that I am using try, catch so is there any way to print the output of $Appfilter to offComp&programsALLO.txt ? The text file just prints the value of $Appfilter.
The output should ideally look like:
Computers:
"name of computer" followed by "programs allowed"
Here is the code:
Get-ADComputer -Filter * | Select-Object -ExpandProperty Name | Out-File .\ADcomputers.txt
$LaunchLine = 'powershell.exe -Version 4.0 -Command "& {netsh advfirewall set allprofiles state off}"'
$Appfilter = 'powershell.exe -Version 4.0 -Command "& {Get-NetFirewallApplicationFilter -program * | fl program}"'
$ComputerList = Get-Content .\adcomputers.txt
foreach($Computer in $ComputerList) {
[String]$wmiPath = "\\{0}\root\cimv2:win32_process" -f $computer
try {
[wmiclass]$Executor = $wmiPath
$executor.Create($LaunchLine, $Appfilter)
} catch {
Add-Content offComp&programsALLO.txt "computers:$Computer, $Appfilter "
}
}
I would use Invoke-Command with the -ComputerName parameter if possible:
#store AD Computer names in an array
$computerList = (Get-ADComputer -Filter *).Name
#declare results arrays
$results = #()
$offline = #()
#for each computer
foreach($computer in $computerList) {
#if computer responds to ping
if(Test-Connection $computer -Count 2 -Quiet -ErrorAction SilentlyContinue) {
#disable firewall
Invoke-Command -ComputerName $computer -ScriptBlock {
netsh advfirewall set allprofiles state off
} | Out-Null
#store retrieved authorized programs list in an array
$programs = Invoke-Command -ComputerName $computer -ScriptBlock {
(Get-NetFirewallApplicationFilter).Program
}
#build results object and add it to results array
$results += [PSCustomObject]#{
ComputerName = $computer
Programs = $programs -join ";"
}
} else {
#build results object and add it to offline array
$offline += [PSCustomObject]#{
ComputerName = $computer
Status = "OFFLINE"
}
}
}
#export results to files
$results | Out-File "report.txt"
$offline | Out-File "offline.txt"

Powershell passing arguments in ScriptBlock

I'm trying to get the last write time on a file from a remote server.
This doesn not work:
$server = "MyServerName"
$lastWrite = Invoke-Command -Computername $server -ScriptBlock {Get-ChildItem "\\$args[0]\hot.war" } -argumentlist $server | select -Property LastWriteTime
This does work:
$lastWrite = Invoke-Command -Computername $server -ScriptBlock {Get-ChildItem "\\MyServerName\hot.war" } -argumentlist $server | select -Property LastWriteTime
Can anyone help make the first set work?
Be careful with variables in strings: "\\$args[0]\hot.war" will be expanded to \\MyServerName[0]\hot.war.
Use "\\$($args[0])\hot.war" to be sure that $args[0] will be treated as a single expression.
See: http://blogs.msdn.com/b/powershell/archive/2006/07/15/variable-expansion-in-strings-and-herestrings.aspx
Another way, if you are using PowerShell 3. You can do something like this:
$lastWrite = Invoke-Command -Computername $server -ScriptBlock {
Get-ChildItem "\\$using:server\hot.war"
} | select -Property LastWriteTime
You will want to add the server variable into your first line...
$server = "MyServerName"
$lastWrite = Invoke-Command -Computername $server -ScriptBlock {Get-ChildItem "\\$server\hot.war" } -argumentlist $server | select -Property LastWriteTime