Check for DNS record using PowerShell 2.0 - powershell

What could be the best way to resolve a computer name apart from using:
[System.Net.DNS]::GetHostByName('MachineName').HostName
I dont want to import any specific DNS Modules.

You can try the GetHostEntry method:
[Net.DNS]::GetHostEntry("MachineName")
Another way would be to ping it using Test-Connection cmdlet, see this tip

I was in a case where I had to query a specific DNS server, which is not possible directly with .net / powershell. So I ended up with using the good old nslookup :
$client="10.110.10.10"
$ns="10.20.1.10"
(nslookup $client $ns |sls name).toString().split(":")[1].trim()

The following 2 ways to resolve IP's to DNS addresses are the only ones.
It's how you use it that counts.
[Net.DNS]::GetHostEntry("MachineName")
[System.Net.DNS]::GetHostByName('MachineName').HostName
Like I said, It's how you use them.
I have written a script for doing just this.
It takes a list of IP addresses and resolves there DNS.
Later in the script it converts the output to an excel sheet, showing you the results.
Based upon filters you can set the layout.
Now I know not all IP's will be resolved with these methods, that's why I included a function in my script that filters out unresolved IP's and places them to the bottom of the excel sheet.
(Giving every IP a direct link to who.is/whois/ipadress
Here's the script, íf you are interested.
#Get current date
$Date = date -format yyyy-MM-dd
$Company = "Company"
$Company2 = "Company2"
########################
#Define all Paths.
$Path = "C:\inetpub\wwwroot\BlockedIP" #This is where your file's will be saved.
md "$Path\HTML\$Date" -Force |Out-Null
$path2 = "$Path\HTML\$Date"
$PathWeb = "/ResolvedIp/HTML/$Date"
########################
#Define File's used or created in this script.
$File = "$Path\IP-$Date.txt"
$FileHtml = "$Path2\IP-$Date.htm"
$FileXML = "$Path\IP-$Date.xlsx"
$FileHTMLWeb = "$PathWeb\IP-$date.htm"
######################################
#Define error actions.
$erroractionpreference = "SilentlyContinue"
###########################################
#Since the script used COM objects it will need the following 2 folders:
#(32Bit)
MD "C:\Windows\System32\config\systemprofile\Dektop" -force
MD "C:\Windows\System32\config\systemprofile\AppData\Local\Microsoft\Windows\Temporary Internet" -force
#(64Bit)
MD "C:\Windows\SysWOW64\config\systemprofile\Desktop" -force
MD "C:\Windows\SysWOW64\config\systemprofile\AppData\Local\Microsoft\Windows\Temporary Internet" -force
#Once successfull the script will run without a problem if scheduled.
cls
(gc $File) | ? {$_.trim() -ne "" } | set-content $File
$IPCount = (gc $File)
$IPCount = $IPCount.count
write "$IPCount unique IP addresses detected."
#Define error actions.
$erroractionpreference = "SilentlyContinue"
#Get content from given IP list.
$colComputers = #(gc $File | sort |Select -unique)
$SourceCount = $colComputers.Count
write "$SourceCount IP's detected."
Function Set-KnownIPs{
Param([Object]$DNSLookupObject)
Switch($DNSLookupObject){
{$_.Source -Match "(108.162.254|141.101.(?:104|105)|199.27.128|173.245(?:53|52|51))"}{$_.HostName = "CloudFlare, Inc."}
{$_.Source -Match "(64.18.[0-18])"}{$_.HostName = "Google, Inc."}
{$_.Source -Match "(192.168|127.0.0)"}{$_.HostName = "Internal Infrastructure"}
}
$DNSLookupObject
}
#Get DNS Results
$Progress=1
$DNSResults = $colComputers | %{
Write-Progress -Activity "Creating a usable 'Blocked IP' list ($Progress/$sourcecount)" -PercentComplete ($Progress/$sourceCount*100) -Status "Please stand by"
try {
($dnsresult = [System.Net.DNS]::GetHostEntry($_))
}
catch {
$dnsresult = "Fail"
}
Set-KnownIPs -DNSLookupObject ([PSCustomObject][Ordered]#{
Source=$_.ToUpper()
HostName=$(if(!([string]::IsNullOrEmpty($dnsresult.HostName))){$dnsresult.HostName})
IPAddress=$(if(!([string]::IsNullOrEmpty($dnsresult.AddressList))){$dnsresult.AddressList[0].ToString()})
})
$Progress++
}
$Keywords = #("Google","Cloudflare","Cloud","Ping",
"Easy-Voyage","McAfee","Pingdom","Panopta","Scoot","Uniglobe",
"Internal")
$Filter = "($(($Keywords|%{[RegEx]::Escape($_)}) -join "|"))"
$DNSLookupFailed = $DNSResults |
?{[string]::IsNullOrEmpty($_.HostName) -and !($_ -match $filter)}
$DNSWithKeyword = $DNSResults |
?{$_ -match $Filter}
$DNSNoKeyword = $DNSResults |
?{!($_.HostName -match $Filter) -and !([string]::IsNullOrEmpty($_.IPAddress))}
#$count = ($DNSResults|?{$_ -match $filter}).count
$count = $SourceCount
#####################
#start Excel.
$a = New-Object -comobject Excel.Application
# set interactive to false so nothing from excel is shown.
$a.DisplayAlerts = $False
$a.ScreenUpdating = $True
$a.Visible = $True
$a.UserControl = $True
$a.Interactive = $True
###########################
#Create sheets in Excel.
$b = $a.Workbooks.Add()
$c = $b.Worksheets.Item(1)
$c.Activate() | Out-Null
#Create a Title for the first worksheet and adjust the font
$c.Cells.Item(1,1)= "Blocked IP's $Date"
$c.Cells.Item(1,1).Font.ColorIndex = 55
$c.Cells.Item(1,1).Font.Color = 8210719
$c.Cells.Item((3+$DNSWithKeyword.Count+1),1) = "IP's not in whitelist"
$c.Cells.Item((3+$DNSWithKeyword.Count+1),1).Font.ColorIndex = 55
$c.Cells.Item((3+$DNSWithKeyword.Count+1),1).Font.Color = 8210719
$c.Cells.Item((3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+3),1)= "IP's without DNS return"
$c.Cells.Item((3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+3),1).Font.ColorIndex = 55
$c.Cells.Item((3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+3),1).Font.Color = 8210719
#######################################
$range = $c.Range("a1","e1")
$range.Style = 'Title'
$range.Select()
$range.MergeCells = $true
$range.VerticalAlignment = -4108
################################
$Linkedin = "https://www.linkedin.com/profile/view?id=96981180" #Look me up! :D
#Define row to be used for linkedin link.
$CounterRow = $Count+5
######################
#Define subjects.
$c.Name = "Blocked IP's ($Date)"
$c.Cells.Item(2,1) = "Given IP"
$c.Cells.Item(2,2) = "Resolved DNS"
$c.Cells.Item(2,3) = "Returned IP"
$c.Cells.Item(2,5) = "$Company"
$c.Cells.Item((3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+$DNSLookupFailed.Count+5),1) = "Created by"
########################################
$link = "http://www.$Company"
$link2 = "$Linkedin"
$r = $c.Range("E2")
[void]$c.Hyperlinks.Add($r, $link)
$r = $c.Range("A$(3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+$DNSLookupFailed.Count+5)")
[void]$c.Hyperlinks.Add($r, $link2)
###################################
#Define cell formatting from subjects.
$c.Range("A2:E2").Interior.ColorIndex = 6
$c.Range("A2:E2").font.size = 13
$c.Range("A2:E2").Font.ColorIndex = 1
$c.Range("A2:E2").Font.Bold = $True
###################################
#Define the usedrange, excluding header and footer rows
$KeyRange = $c.Range("A3:c$(3+$DNSWithKeyword.Count)")
$NoKeyRange = $c.Range("A$(3+$DNSWithKeyword.Count+2):c$(3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+2)")
$NoDNSRange = $c.Range("A$(3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+4):c$(3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+$DNSLookupFailed.Count+4)")
$SheetRange = $c.Range("A3:e$(4+$DNSWithKeyword.Count+$DNSNoKeyword.Count+$DNSLookupFailed.Count+4)")
$Investigate = $c.Range("c$(3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+4):c$(3+$DNSWithKeyword.Count+$DNSNoKeyword.Count+$DNSLookupFailed.Count+4)")
################################
#Set background color for the IP list.
$SheetRange.interior.colorindex = 6
$KeyRange.interior.colorindex = 4
$NoKeyRange.interior.colorindex = 15
$NoDNSRange.interior.colorindex = 8
####################################
#Populate data into spreadsheet
$DNSWithKeyword | Select Source, HostName, IPAddress | Sort HostName -Descending |
ConvertTo-Csv -Delimiter "`t" -NoTypeInformation |
Select -Skip 1 | Clip
$c.Paste($KeyRange,$false)
$DNSNoKeyword | Select Source, HostName, IPAddress | Sort HostName -Descending |
ConvertTo-Csv -Delimiter "`t" -NoTypeInformation |
Select -Skip 1 | Clip
$c.Paste($NoKeyRange,$false)
$DNSLookupFailed | Select Source, HostName, IPAddress | sort Source -Descending|
ConvertTo-Csv -Delimiter "`t" -NoTypeInformation |
Select -Skip 1 | Clip
$c.Paste($NoDNSRange,$false)
############################
ForEach($Cell in $Investigate){
If([String]::IsNullOrWhitespace($Cell.value2)){
$Cell.Item($_) = "N/A"
[void]$cell.Hyperlinks.Add($Cell)
}
}
###########################################################################
#Define borders here.
$xlOpenXMLWorkbook = 51
$xlAutomatic=-4105
$xlBottom = -4107
$xlCenter = -4108
$xlRight = -4152
$xlContext = -5002
$xlContinuous=1
$xlDiagonalDown=5
$xlDiagonalUp=6
$xlEdgeBottom=9
$xlEdgeLeft=7
$xlEdgeRight=10
$xlEdgeTop=8
$xlInsideHorizontal=12
$xlInsideVertical=11
$xlNone=-4142
$xlThin=2
#########
$selection = $c.range("A2:C$(1+$DNSResults.Count-9)")
$selection.select() |out-null
$selection.HorizontalAlignment = $xlRight
$selection.VerticalAlignment = $xlBottom
$selection.WrapText = $false
$selection.Orientation = 0
$selection.AddIndent = $false
$selection.IndentLevel = 0
$selection.ShrinkToFit = $false
$selection.ReadingOrder = $xlContext
$selection.MergeCells = $false
$selection.Borders.Item($xlInsideHorizontal).Weight = $xlThin
#############################################################
#Define the usedrange for autofitting.
$d = $c.UsedRange
#################
#Make everything fit in it's cell.
$d.EntireColumn.AutoFit() | Out-Null
####################################
$c.usedrange | Where{$_.Value2 -match "(\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b)"} |
ForEach{$IPLink = "http://who.is/whois-ip/ip-address/$($Matches[1])";[void]$c.Hyperlinks.Add($_, $IPLink)}
#Define html code for Excel save to .htm.
$xlExcelHTML = 44
#################
#Save final result as an .xlsx file.
$b.SaveAs("$FileXML")
#####################
#Save final result as a .htm file
$b.SaveAs("$FileHTML",$xlExcelHTML)
###################################

In powershell 5.1 you can use
Resolve-DnsName

Related

Optimize for each variable powershell script

$allResources = #()
$subscriptions=Get-AzSubscription
ForEach ($vsub in $subscriptions){
Select-AzSubscription $vsub.SubscriptionID
Write-Host
Write-Host "Working on "$vsub
Write-Host
$allResources += $allResources |Select-Object $vsub.SubscriptionID,$vsub.Name
$result=#()
$webapps = Get-AzWebApp
foreach($webapp in $webapps){
$Tier = (Get-AzResource -ResourceId $webapp.ServerFarmId).Sku.Tier
$SKU = (Get-AzAppServicePlan -ResourceGroupName $webapp.ResourceGroup).Sku.Size
$AppServiceName = (Get-AzAppServicePlan -ResourceGroupName $webapp.ResourceGroup).Name
$obj = [PSCustomObject]#{
TenantId = $vsub.TenantId
SubscriptionName = $vsub.Name
WebappName = $webapp.Name
ResourceGroup = $webapp.ResourceGroup
Hostname = $WebApp.DefaultHostName
PricingTier = $Tier
SKU = ($SKU -join ',')
AppServiceName = ($AppServiceName -join ',')
#State = $webapp.State
#Location = $webapp.Location
#AppType = $webapp.Kind
}
$result += $obj
$result | Export-Csv -Path "E:\webapps_filter.csv" -Append -NoTypeInformation
$input = 'E:\webapps_filter.csv'
$inputCsv = Import-Csv $input | Sort-Object * -Unique
$inputCsv | Export-Csv "E:\webapps.csv" -NoTypeInformation}}
Right now I am using the above script to fetch all the required data of web apps from all the subscriptions. Currently, the script is taking time to execute, I need to optimize it and also the script gives a duplicate output so in last have added the filter to sort out it by unique entry.
It seems you are adding stuff to an array variable $allResources you don't use, so get rid of that.
Instead of the costly (time/memory) $result += $obj, better let PowerShell collect the objects using $result = foreach(..)
You are appending a temporary file inside the foreach loop on each iteration, then import this file and filter it on all properties to become unique.
again, inside the loop you are exporting this uniqified data to a CSV file on every iteration
You are calling upon cmdlet Get-AzAppServicePlan twice to get different properties. Use it only once would save time
as aside, you should not use a self-defined variable called $input as this is an Automatic variable
Try:
$subscriptions = Get-AzSubscription
$result = foreach ($vsub in $subscriptions){
Select-AzSubscription $vsub.SubscriptionID
Write-Host
Write-Host "Working on $($vsub.Name)"
Write-Host
foreach($webapp in (Get-AzWebApp)){
$Tier = (Get-AzResource -ResourceId $webapp.ServerFarmId).Sku.Tier
$Plan = Get-AzAppServicePlan -ResourceGroupName $webapp.ResourceGroup
# output the object so it gets collected in $result
[PSCustomObject]#{
TenantId = $vsub.TenantId
SubscriptionName = $vsub.Name
SubscriptionID = $vsub.SubscriptionID
WebappName = $webapp.Name
ResourceGroup = $webapp.ResourceGroup
Hostname = $webapp.DefaultHostName
PricingTier = $Tier
SKU = #($Plan.Sku.Size) -join ','
AppServiceName = #($Plan.Name) -join ','
#State = $webapp.State
#Location = $webapp.Location
#AppType = $webapp.Kind
}
}
}
# sort unique and export the file
$result | Sort-Object * -Unique | Export-Csv -Path "E:\webapps.csv" -NoTypeInformation

Powershell: How to add values to Object with only 1 header

Got a .ps where im getting alarmgroups from several files. Im trying to add them to an Object but the Problem is every new file hes adding another header into the Object. Is there a possibility, adding the header only 1 time. Append my data to the Object and when hes finished sorting the hole Object?
My Code.
$rootPath = $PSScriptRoot
if ($rootPath -eq "") {
$rootPath = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
}
$alarmPath = "$rootPath\Alarmgroups"
$mdi_alarms_template = "$rootPath\tmpl\mdi-alarms.tmpl.html"
$mdi_alarms = "$rootPath\mdi-alarms.html"
$fileNames = Get-ChildItem -Path $alarmPath -Filter *.algrp
$AlarmgroupIndexString = $LanguageIDString = $tmpString = $ID_string = $html_output= ""
$MachineCode = "Out_2.Alarm.Current"
$BitNo = $Element = $Format2Element = $Format3BitID =0
$BitID = $Format3TextID = 1
$list = New-Object System.Collections.ArrayList
Clear-Content "$rootPath\test.txt"
Clear-Content "$rootPath\list.txt"
Clear-Content "$rootPath\output.txt"
# Parse each alarm group file in the project
foreach ($file in $fileNames) {
$Content = [xml](Get-Content -Path $file.FullName)
$ns = New-Object System.Xml.XmlNamespaceManager($Content.NameTable)
$ns=#{asdf="http://asdf-automation.co.at/AS/VC/Project"}
$AlarmgroupIndex = Select-Xml -Xml $Content -XPath "//asdf[contains(#Name,'Index')]" -namespace $ns | select -ExpandProperty node
$AlarmgroupIndexString = $AlarmgroupIndex.Value
$AlarmgroupLanguageText = Select-Xml -Xml $Content -XPath "//asdf:TextLayer" -namespace $ns | select -ExpandProperty node
$AlarmgroupIndexMap = Select-Xml -Xml $Content -XPath "//asdf:Index" -namespace $ns | select -ExpandProperty node
$LUT =#{}
$AlarmgroupIndexMap | foreach{
$LUT.($_.ID) = $_.Value
}
$tmpArray =#()
$list = $AlarmgroupLanguageText | foreach{
$LanguageIDString = $_.LanguageId
$AlarmgroupTextLayer = Select-Xml -Xml $Content -XPath "//asdf:TextLayer[#LanguageId='$LanguageIDString']/asdf:Text" -namespace $ns | select -ExpandProperty node
$AlarmgroupTextLayer | foreach{
if($LUT.ContainsKey($_.ID))
{
$ID_string = $LUT[$_.ID]
}
[pscustomobject]#{
Language = $LanguageIDString
GroupID = $AlarmgroupIndexString
TextID = $ID_string #-as [int]
Text = $_.Value
}
$ID_string =""
}
$LanguageIDString=""
}
$list = $list |Sort-Object -Property Language, GroupID, {$_.TextID -as [int]}
# $list = $list |Sort-Object -Property #{Expression={$_.Language}}, #{Expression={$_.TextId}} , #{Expression={$_.TextID -as [int]}}
$list | Out-File "$rootPath\list.txt" -Append -Encoding utf8
Output:
GroupID Language TextID Text
------- -------- ------ ----
24 aa Group
24 aa 0
24 aa 1
24 aa 2
24 aa 3
24 aa 4
24 aa 5
24 aa 6
24 aa 7
24 aa 8
24 aa 9
24 aa 10
GroupID Language TextID Text
------- -------- ------ ----
24 ar Group
24 ar 0
24 ar 1
24 ar 2
24 ar 3
24 ar 4
24 ar 5
24 ar 6
24 ar 7
So i have several headers in my outputfile. Is it possible to erase them or add elements to the Object without the header. Tried several solution nothing worked.
If i understand it correctly im generating an Object and add it to an object with all values incl. header.
[pscustomobject]#{
Language = $LanguageIDString
GroupID = $AlarmgroupIndexString
TextID = $ID_string #-as [int]
Text = $_.Value
You can assign all the output from the foreach loop to a single variable and then move the file-write logic to the end of the script where you can output it all at once:
# Assign results of entire `foreach(){}` statement to `$combinedLists`
$combinedLists = foreach ($file in $fileNames) {
# XML navigation + object creation + assignment to `$list` still goes here
# We sort and then instead of assigning the output to a variable directly,
# we just let it "bubble up" from here to the `$combinedList` assignment
$list |Sort-Object -Property Language, GroupID, {$_.TextID -as [int]}
}
# Now we can write everything to file at once (overwrites existing contents)
$combinedLists |Out-File "$rootPath\list.txt" -Force -Encoding utf8

CSV misalignment when reading in powershell

I have a CSV with a lot of headers. It ranges from Column A to AZ. I need to read only the first column of the CSV.
My issue is the last column (comments) bleeds into the first column when opened in notepad++ and it appears to show that it is apart of Column one (host name). When I run my code it reads it as notepad++ does.
I originally convert this from an .xls to a CSV file, is there a way to ensure the last column does not wrap around?
#region - Convert to CVS
$strFileName = "C:\working\Server Count & Status Check ARC 0219183.xlsx"
$strSheetName = 'SCI$'
$strProvider = "Provider=Microsoft.ACE.OLEDB.12.0"
$strDataSource = "Data Source = $strFileName"
$strExtend = "Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';"
$strQuery = "Select * from [$strSheetName]"
$objConn = New-Object
System.Data.OleDb.OleDbConnection("$strProvider;$strDataSource;$strExtend")
$sqlCommand = New-Object System.Data.OleDb.OleDbCommand($strQuery)
$sqlCommand.Connection = $objConn
$objConn.open()
$da = New-Object system.Data.OleDb.OleDbDataAdapter($sqlCommand)
$dt = New-Object system.Data.datatable
$da.fill($dt)
$dt | Export-Csv "C:\working\Server Count & Status Check ARC 0219183.csv" -
NoTypeInformation
$objConn.close()
#endregion
Original Spreadsheet
After trying to gather first column(hostname)
$array=#{}
$ServerStatus = Get-Content "C:\Users\user\Desktop\Scripts\Linux Server
Compare\Server Count & Status Check ARC 0219183.csv" | select -skip 1 |
ConvertFrom-Csv -Header "HostName","Business Application","Technical
Function","Location","Environment","Day Number","Slot
Number","SlotTime","Description","DNS Name","Key Server","Host Name","Public
IP","Server Type","Build Date","Builder","Product Name","Serial
No","Enclosure","Bay","CPU Model","CPU Socket","CPU Cores","Logical
CPU","Memory","Up Time","Kernel Version","OS Type","Version","Patch
level","Multipath Disks?","Multipath Checker?","Customized Fsck?","Splx
Installed?","Splx Running?","Suse Manager Status","RHN Running ?","RHN
Autostart?","Installed Kernel","Available Kernel in
/boot","Hardened","Syslog
Config correct ?","Syslog Running ?","Patrol Running?","Splunk
Installed?","Splunk Running?","Puppet Installed?","Puppet
Running?","Centrify
Version","VM Tools Installed?","VM Tools Running?","Comments"
$ServerStatusObj = new-object Object
$ServerStatusObj | add-member -membertype NoteProperty "Name" -value ""
$ServerStatusObj | add-member -membertype NoteProperty "Origin" -value ""
$array=#{name = $ServerStatus.HostName}
foreach ($name in $array.name){
if($name -ne $null){
$Value = $name
if($name -ne $null){
$ServerStatusObj.name =$Value
$ServerStatusObj.Origin = " Linux Servers"
} #End of IF
else {Write-Output "null"}
Write-Output $ServerStatusObj | export-csv
"C:\Users\user\Desktop\Scripts\Linux Server Compare\ServerStatusParse.csv" -notypeinformation -Append
}

In Powershell, how do I print out only the data from today(or a specific date range)?

I have a shared Outlook folder, where I need to extract 6-digit numbers from Email subject lines. So I use the following script :
$Outlook = New-Object -ComObject Outlook.Application
$Namespace = $outlook.GetNameSpace("MAPI")
$SharedMB = $NameSpace.Folders | Where{$_.Name -match "FDA UFMS User Provision"}
$OtherFldr = $SharedMB.Folders | Where{$_.Name -match "Inbox"}
[datetime]$StartDate = ([datetime]::now.ToShortDateString())
$TodaysMail = #()
for($i = ($OtherFldr.Items.count - 1);$i -ge 0;$i--){
$Current = $OtherFldr.Items.item($i)
if($Current.senton -lt (get-date $StartDate)){break}
else { $OtherFldr.Items | %{ $RESULT=[Regex]::Match ($_.TaskSubject, "Request\s\d{6}"); if ($RESULT.Success){$RESULT.
Value}} | %{$Result=[Regex]::Match($_, "\d{6}"); if ($RESULT.Success){$RESULT.Value}} | Out-File C:\Temp\powerfish4.txt
-Append }
$TodaysMail += $Current
}
But this throws up a strange error to me :
The funny thing, is that if I simply dump all the numbers into a text file, it does not have this permission error. That is, I can run this script just fine :
$OtherFldr.Items | %{ $RESULT=[Regex]::Match($_.TaskSubject, "Request\s\d{6}"); if ($RESULT.Success)
{$RESULT.Value}} | %{$Result=[Regex]::Match($_, "\d{6}"); if($RESULT.Success){$RESULT.Value}} | Out-File C:\Temp\powerfish2.txt -Append
I'm currently trying to play with Outlook's offline-mode.
any tips appreciated , thanks
This is just an assumption but maybe trying to copy the entire item requires Outlook to be online.(Maybe Outlook is not caching the entire item)
$Current = $OtherFldr.Items.item($i)
I don't have a list of properties that Outlook holds as a cache but maybe just dealing with tasksubject and senton might be available in cache.
Also modified the for loop to make it more simple.
$Outlook = New-Object -ComObject Outlook.Application
$Namespace = $outlook.GetNameSpace("MAPI")
$SharedMB = $NameSpace.Folders | Where{$_.Name -match "FDA UFMS User Provision"}
$OtherFldr = $SharedMB.Folders | Where{$_.Name -match "Inbox"}
[datetime]$StartDate = ([datetime]::now.ToShortDateString())
ForEach($Item in $OtherFldr.Items){
if($Item.senton -lt (get-date $StartDate)){break}
if($Item.TaskSubject -Match "Request\s\d{6}")
{
$Result=[Regex]::Match($Item.TaskSubject, "\d{6}");
if($RESULT.Success){
$RESULT.Value | Out-File C:\Temp\powerfish4.txt -Append
}
}
}

Format display in powershell

I have a csv file with the following information:
OS Name: Microsoft© Windows Server© 2008 Standard
OS Version: 6.0.6002 Service Pack 2 Build 6002
System Manufacturer: IBM
System Model: IBM 3850 M2 / x3950 M2 -[7233Z1H]-
I need to use powrshell to read and format the display.. My existing code is this:
$Array = #()
Get-Content <txtfilename> | foreach {
$Test = $_
$Title = $Test.split(":")[0]
$Content = $Test.split(":")[1]
$Obj = New-Object System.Object
$Obj | Add-Member -MemberType NoteProperty -value $Title -Name Title
$Obj | Add-Member -MemberType NoteProperty -value $Content -Name Value
$Array += $Obj
}
$Array | Select Title,Value | Export-Csv <csvfilename> -NoTypeInformation
It displays the information as follows listed:
Title Content
OS Name Microsoft? Windows Server? 2008 Standard
OS Version 6.0.6002 Service Pack 2 Build 6002
System Manufacturer IBM
System Model IBM 3850 M2 / x3950 M2 -[7233Z1H]-
I need the information displayed in a single line like this:
ServerName, OS Name , OS Version, System Manufacture, Sytem model,
TestServer1, Microsoft Windows, 6.0.6002 Service Pack 2, IBM, IBM 3850
Thanks
Here's a second answer for the more advanced case, where you don't know how many unique headers you have or what they're called. As long as they're consistently the same and in the same order, the following will work:
$filePath = "C:\users\chris\desktop\info.txt"
$headers = #()
[int]$headerCount = 0
$endUnique = $false
Get-Content $filePath | % {
$header = ($_.split(':')[0] -replace '\s+', ' ').Trim()
if (($headers -notcontains $header) -and (!$endUnique)){
$headers += $header
$headerCount += 1
}
else{
$endUnique = $true
}
}
$headerRow = ""
$headers | % {$headerRow += $_ + ","}
$headerRow = $headerRow.Substring(0,$headerRow.Length-1)
[int]$i = 1
$outString = ""
Get-Content $filePath | % {
$lineContent = ($_.split(':')[1] -replace '\s+', ' ').Trim()
if ($i -lt $headerCount){
$outstring += $linecontent + ','
$i += 1
}
else{
$outstring += $linecontent + "`r`n"
$i = 1
}
}
$outstring = $headerRow+ "`r`n"+$outstring
I'd like to see the other answers from more advanced PowerShell users.
First, just a quick correction. You say you have a CSV. It looks like you have a formatted text file and you want to make a CSV out of it.
Following that assumption, something like this should get you started. It assumes that the text document has either only those 4 items in it, or those 4 items are repeated multiple times - always in the same order, and without a space in between them. Reformatting text files is never fun without a bunch of examples of how they could look.
That being said, the following should get you started.
[int]$i = 1
$outString = ""
Get-Content C:\users\chris\desktop\info.txt | % {
#Take the line, remove the title, remove whitespaces from inside of the line and trim whitespaces from the outside.
$lineContent = ($_.split(':')[1] -replace '\s+', ' ').Trim()
#Chunk them together...
if ($i -lt 4){
$outstring += $linecontent + ','
$i += 1
}
#or insert a return, new line
else{
$outstring += $linecontent + "`r`n"
$i = 1
}
}
#Add a header row. Now $outstring is your CSV formatted text.
$outstring = "OSName,OSVersion,SystemMfg,SystemModel`r`n"+$outstring
$object = New-Object System.Object
Get-Content TestServer1-OSInfo.txt | % {
If($_.Contains(":")){
$Left = $_.split(":")[0].TrimStart().TrimEnd()
$Right = $_.split(":")[1].TrimStart().TrimEnd()
$object | Add-Member -type NoteProperty -name $Left -value $Right
}
}
$object | Export-Csv TestServer1-OSInfo.csv -NoTypeInformation