When I use this command :
ipptool -tv -I -d "doc-uri=http://www.nice.com/123.txt"
The output results is:
media-col (collection) = {media-source=auto}
job-uri (uri) = ipp://192.168.0.1/ipp/print/job-0030
job-id (integer) = 30
job-state (enum) = processing
job-state-reasons (keyword) = none
job-state-message (textWithoutLanguage) =
EXPECTED: STATUS successful-ok (got successful-ok-ignored-or-substituted-attributes)
How Can I use powershell to get the string "30" ?
30 is the value of job-id
Assuming the output result of your ipptool is in a text file called "C:\Test\Iptool.txt" you could use this:
$iptoolOutput = Get-Content "C:\Test\Iptool.txt" -Raw
$result = ''
if ($iptoolOutput -match 'job-id.+=\s*(\d+)') {
$result = $matches[1]
}
$result
Using Select-String:
$ipptool = $(ipptool -tv -I -d "doc-uri=http://www.nice.com/123.txt")
[Int]($ipptool | Select-String "job-id \(integer\) =\s*(\d+)").Matches.Groups[1].Value
You can use Match and Split
$Data = ipptool -tv -I -d "doc-uri=http://www.nice.com/123.txt"
($Data | ? {$_ -match 'job-id'}).Split("=")[1]
Related
I'm traing to start 2 remote packet captures at same time on a winServer2016 with two nics, with tshark 3.4.5 and powershell 7.2.1.
The problem is that I can't found the correct sintax to pass variables to tshark...
$ScriptPath = "E:\CC12\Scripts\TShark"
$dateForDirLogs = (Get-Date).ToString('yyyy-MM-dd-HH')
$dateForLogs = (Get-Date).ToString('yyyy-MM-dd-HH.mm')
$logDir = "$ScriptPath\Logs"
$MyServer = "SRV1"
$LogFile = "$logDir\$($MyServer)_$($dateForLogs).txt"
$MySession = New-PSSession $MyServer -ConfigurationName PowerShell.7.2.1
Invoke-Command -Session $MySession -ScriptBlock {
$CptPathName = "E:\Captures\$using:dateForDirLogs"
$JobLogFile = "$CptPathName\RmJobsLog.txt"
$HName = $using:MyServer
$CptFilePub = "$CptPathName\$($HName)_PUB_$using:dateForLogs.pcapng"
$CptFilePri = "$CptPathName\$($HName)_PRI_$using:dateForLogs.pcapng"
$TsharkBin = "C:\Program Files\Wireshark\tshark.exe"
[string]$NicPub = & $TsharkBin -D | Select-String "Public"
$ifNumPub = $NicPub.Split("\")[0]
$NicPub = $NicPub.Replace($ifNumPub,'')
$NicPub = $NicPub.Replace(' (Public)','')
[string]$NicPri = & $TsharkBin -D | Select-String "Private"
$ifNumPri = $NicPri.Split("\")[0]
$NicPri = $NicPri.Replace($ifNumPri,'')
$NicPri = $NicPri.Replace(' (Private)','')
$FilterPub = "dst net 10.49.94.0/24"
$FilterTimePub = 300
$FilterSizePub = 307200
$FilterPri = "dst net 10.56.128.0/25"
$FilterTimePri = 300
$FilterSizePri = 307200
# echo variables
$CptPathName
$JobLogFile
$HName
$CptFilePub
$CptFilePri
$NicPub
$NicPri
$FilterPub
$FilterPri
$CptCMDs = #(
"-i $NicPub -f $FilterPub -a duration:$FilterTimePub -w $CptFilePub"
"-i $NicPri -f $FilterPri -a duration:$FilterTimePri -w $CptFilePri"
)
$CptCMDs | ForEach-Object -Parallel {
$TsharkBin = "C:\Program Files\Wireshark\tshark.exe"
& $TsharkBin $_
} -ThrottleLimit 2
}
I've tried to quoting the "qoutes" like that, but doesn't works:
$NicPub = "`"$NicPub`""
Seems that tshark reads the $CptCMDs as a single parameter the interface name! Seems skips its commands switch...
This is the output, if I ran the script interactively:
E:\Captures\2022-09-16-15
E:\Captures\2022-09-16-15\RmJobsLog.txt
SRV1
E:\Captures\2022-09-16-15\SRV1_PUB_2022-09-16-15.06.pcapng
E:\Captures\2022-09-16-15\SRV1_PRI_2022-09-16-15.06.pcapng
"\Device\NPF_{3578AB86-0318-4116-818C-87BC171F2B6F}"
"\Device\NPF_Loopback"
dst net 10.49.94.0/24
dst net 10.56.128.0/25
Capturing on ' \Device\NPF_{3578AB86-0318-4116-818C-87BC171F2B6F} -f dst net 10.49.94.0/24 -a duration:300 -w E:\Captures\2022-09-16-15\SRV1_PUB_2022-09-16-15.06.pcapng'
Capturing on ' \Device\NPF_{34234H86-5488-5546-212C-57867G57FR2Y} -f dst net 10.56.128.0/25 -a duration:300 -w E:\Captures\2022-09-16-15\SRV1_PRI_2022-09-16-15.06.pcapng'
tshark: The capture session could not be initiated on interface ' \Device\NPF_{3578AB86-0318-4116-818C-87BC171F2B6F} -f dst net 10.49.94.0/24) -a duration:300 -w E:\Captures\2022-09-16-15\SRV1_PUB_2022-09-16-15.06.pcapng' (Error opening adapter: The filename, directory name, or volume label syntax is incorrect. (123)).
Please check that you have the proper interface or pipe specified.
0 packets captured
tshark: The capture session could not be initiated on interface ' \Device\NPF_{34234H86-5488-5546-212C-57867G57FR2Y} -f dst net 10.56.128.0/25 -a duration:300 -w E:\Captures\2022-09-16-15\SRV1_PRI_2022-09-16-15.06.pcapng' (Error opening adapter: The filename, directory name, or volume label syntax is incorrect. (123)).
Please check that you have the proper interface or pipe specified.
0 packets capture
Can Anyone help me?
Somehow the arguments would have to be split into a list like:
$list1 = 1,2,3
$list2 = 4,5,6
$prog = 'echoargs'
$list1,$list2 | % { & $prog $_ }
Arg 0 is <1>
Arg 1 is <2>
Arg 2 is <3>
Arg 0 is <4>
Arg 1 is <5>
Arg 2 is <6>
Try it this way:
$list1 = '-i',$NicPub,'-f',$FilterPub,'-a',"duration:$FilterTimePub",'-w',$CptFilePub
$list2 = '-i',$NicPri,'-f',$FilterPri,'-a',"duration:$FilterTimePri",'-w',$CptFilePri
$CptCMDs = $list1,$list2
$CptCMDs | ForEach-Object -Parallel {
# ...
I'm trying to insert my CSV into my SQL Server database but just wondering how can I subtract the last three character from CSV GID column and then assigned it to my $CSVHold1 variable.
My CSV file look like this
GID Source Type Message Time
KLEMOE http://google.com Od Hello 12/22/2022
EEINGJ http://facebook.com Od hey 12/22/2022
Basically I'm trying to get only the first three character from GID and pass that value to my $CSVHold1 variable.
$CSVImport = Import-CSV $Global:ErrorReport
ForEach ($CSVLine1 in $CSVImport) {
$CSVHold1 = $CSVLine1.GID | ForEach-Object { $_.$GID = $_.$GID.subString(0, $_.$GID.Length - 3); $_ }
$CSVGID1 = $CSVLine1.GID
$CSVSource1 = $CSVLine1.Source
$CSVTYPE1 = $CSVLine1.TYPE
$CSVMessage1 = $CSVLine1.Message
}
I'm trying to do like above but some reason I'm getting an error.
You cannot call a method on a null-valued expression.
Your original line 3 was/is not valid syntax as Santiago pointed out.
$CSVHold1 = $CSVLine1.GID | ForEach-Object { $_.$GID = $_.$GID.subString(0, $_.$GID.Length - 3); $_ }
You are calling $_.$GID but you're wanting $_.GID
You also don't need to pipe the object into a loop to achieve what it seems you are asking.
#!/usr/bin/env powershell
$csvimport = Import-Csv -Path $env:HOMEDRIVE\Powershell\TestCSVs\test1.csv
##$CSVImport = Import-CSV $Global:ErrorReport
ForEach ($CSVLine1 in $CSVImport) {
$CSVHold1 = $CSVLine1.GID.SubString(0, $CSVLine1.GID.Length - 3)
$CSVGID1 = $CSVLine1.GID
$CSVSource1 = $CSVLine1.Source
$CSVTYPE1 = $CSVLine1.TYPE
$CSVMessage1 = $CSVLine1.Message
Write-Output -InputObject ('Changing {0} to {1}' -f $CSVLine1.gid, $CSVHold1)
}
Using your sample data, the above outputs:
C:> . 'C:\Powershell\Scripts\dchero.ps1'
Changing KLEMOE to KLE
Changing EEINGJ to EEI
Lastly, be aware that that the SubString method will fail if the length of $CSVLine1.GID is less than 3.
this is probably really simple... but how do I check which lines of a log/config file contain any of the strings from a string array?
Example of file (I want lines 3 and 5)
[Privilege Rights]
SeSystemtimePrivilege = *S-1-5-19,*S-1-5-21-2262136377-125853592-2400401627-1119,*S-1-5-32-544
SeDenyNetworkLogonRight = Guest
SeCreatePagefilePrivilege = *S-1-5-32-544
SeDenyServiceLogonRight = *S-1-5-21-2262136377-125853592-2400401627-1119
SeRemoteShutdownPrivilege = *S-1-5-32-544
SeAuditPrivilege = *S-1-5-19,*S-1-5-20
Script I am using:
$SeRightsArray = #(
'SeDenyNetworkLogonRight',
'SeDenyBatchLogonRight',
'SeDenyServiceLogonRight',
'SeDenyInteractiveLogonRight',
'SeDenyRemoteInteractiveLogonRight')
$LocalPolicyExport = gc "C:\local-security-policy.inf"
Foreach($Line in $LocalPolicyExport){
if ($Line -match $SeRightsArray ){
write-host "FOUND - $line"
}
}
Normally I would use something like -contains or -in, but that doesn't work
You can use gc "C:\local-security-policy.inf" | select-string $seRightsArray. No need for a loop
PS C:\> gc .\test.txt|select-string $SeRightsArray
SeDenyNetworkLogonRight = Guest
SeDenyServiceLogonRight = *S-1-5-21-2262136377-125853592-2400401627-1119
I have a URL www.example.com:1234/ and I need to trim above in to 2 variables:
example.com
00234
first digit of port will be replaced by 00
Can this be achieved in PowerShell?
here's one way to do it ... [grin]
# fake reading in a list of URLs
# in real life, use Get-Content
$UrlList = #'
www.example.com:1234/
www3.example.net:9876
www.other.example.org:5678/
'# -split [environment]::NewLine
$Regex = '^www.*?\.(?<Domain>.+):(?<Port>\d{1,}).*$'
$Results = foreach ($UL_Item in $UrlList)
{
$Null = $UL_Item -match $Regex
[PSCustomObject]#{
URL = $UL_Item
Domain = $Matches.Domain
OriginalPort = $Matches.Port
Port = '00{0}' -f (-join $Matches.Port.ToString().SubString(1))
}
}
$Results
output ...
URL Domain OriginalPort Port
--- ------ ------------ ----
www.example.com:1234/ example.com 1234 00234
www3.example.net:9876 example.net 9876 00876
www.other.example.org:5678/ other.example.org 5678 00678
comment out or delete any unwanted properties. [grin]
per request, a simplified version ... [grin]
$UserInput = 'www.example.com:1234/'
$Regex = '^www.*?\.(?<Domain>.+):(?<Port>\d{1,}).*$'
$Null = $UserInput -match $Regex
$Domain = $Matches.Domain
$Port = '00{0}' -f (-join $Matches.Port.SubString(1))
$Domain
$Port
output ...
example.com
00234
hope that helps,
lee
[uri]$url = 'www.example.com:1234/'
$Value1 = ($url.Scheme).Replace('www.','')
$Value2 = "00" + ($url.AbsolutePath).Substring(1).TrimEnd('/')
To offer an improvement to James C.'s answer:
# Input URL string
$urlText = 'www.example.com:1234/'
# Prepend 'http://' and cast to [uri] (System.Uri), which
# parses the URL string into its constituent components.
$urlObj = [uri] "http://$urlText"
# Extract the information of interest
$domain = $urlObj.Host -replace '^www\.' # -> 'example.com'
$modifiedPort = '00' + $urlObj.Port.ToString().Substring(1) # -> '00234'
I have been wrestling with database connection to PostgreSQL from Powershell. I finally am able to connect to and insert into the database. Now I can't figure out how to extract data from a DB select into a variable.
I'm not including my insert for the sake of clarity but will tack it onto this thread later as I know it was super hard to find and may be helpful to someone.
so here's my code:
# use existing 64 bit ODBC System DSN that we set up manually
$DBconn = New-Object -comobject ADODB.Connection
$DBconn.Open("PostgreSQL35W")
$theQuery = "select * from test1"
$theObject = $DBconn.Execute($theQuery) # $theObject is a System.__ComObject
$numRecords = $theObject.RecordCount
write-host "found $numRecords records" # getting -1
$theObject.MoveFirst() # throws no error
# $theValue = $theObject.DataMember # throws no error, but gives no result
$theValue = $theObject.Index[1] # throws "Cannot index into a null array"
write-host($theValue)
try this
replace "#database#" with your database name in $cnString
replace "#server_ip#" with your server ip address in $cnString
replace "#user#" with a valid user in $cnString and $user
replace "#pass#" with a valid pass in $pass
replace "#table#" with a valid table name of your db
replace 5432 with your db port
$cnString = "DRIVER={PostgreSQL Unicode(x64)};DATABASE=#database#;SERVER=#server_ip#;PORT=5432;UID=#user#;"
$user="#user#"
$pass="#pass#"
$conn = New-Object -comobject ADODB.Connection
$conn.Open($cnString,$user,$pass)
$recordset = $conn.Execute("SELECT * FROM #table# limit 1;")
while ($recordset.EOF -ne $True)
{
foreach ($field in $recordset.Fields)
{
'{0,30} = {1,-30}' -f # this line sets up a nice pretty field format, but you don't really need it
$field.name, $field.value
}
'' # this line adds a line between records
$recordset.MoveNext()
}
$conn.Close();
Via psql, which comes with postgresql
$dburl="postgresql://exusername:expw#exhostname:5432/postgres"
$data="select * from extable" | psql --csv $dburl | ConvertFrom-Csv
You must have psql in your path or reference it, its within e.g. C:\Program Files\PostgreSQL\12\bin. Should be able to type "psql" and see output within powershell.
As a warning, expect strings. E.g $data[0].age.GetType() would be string, despite being stored in the database as an integer. You can immediately cast it, cast it later, or hope powershell infers type correctly.
If you want to add back in type information can do e.g.:
$data = $data | %{[pscustomobject]#{name=$_.name;age=[int]$_.age}}
I ended up figuring it out - here's what I did
$conn = New-Object -comobject ADODB.Connection
# use existing 64 bit ODBC System DSN that we set up manually
$conn.Open("PostgreSQL35W")
$recordset = $conn.Execute("SELECT * FROM JobHistory")
while ($recordset.EOF -ne $True)
{
foreach ($field in $recordset.Fields)
{
'{0,30} = {1,-30}' -f # this line sets up a nice pretty field format, but you don't really need it
$field.name, $field.value
}
'' # this line adds a line between records
$recordset.MoveNext()
}
$conn.Close();
Exit
use the dot notation. You don't need to split the data.
$list = New-Object Collections.Generic.List[OnlineCourse]
foreach($element in $results)
{
$tempObj= New-Object OnlineCourse($element.id,$element.courseName,$element.completedRatio,$element.completedRatio,$element.lastActivity, $element.provider)
$list.add($tempObj)
}
I have a slightly different approach to #dog, I couldn't get the --csv to work, so I resorted to tuple only rows returned, then parse them into a List of Classes (which happen to be called OnlineCourses):
class OnlineCourse
{
[int]$id
[string]$email
[string]$courseName
[int]$completedRatio
[datetime]$lastActivity
[String]$provider
OnlineCourse([int]$id,
[string]$email,
[string]$courseName,
[int]$completedPerc,
[datetime]$lastActivity,
[String]$provider) {
$this.id = $id
$this.email = $email.Trim()
$this.courseName = $courseName.Trim()
$this.completedRatio = $completedPerc
$this.lastActivity = $lastActivity
$this.provider = $provider.Trim()
}
}
$connstr="postgresql://exusername:expw#exhostname:5432/postgres"
$data = "select * from onlinecourses" | .\psql -t $connstr
$list = New-Object Collections.Generic.List[OnlineCourse]
foreach ($field in $data) {
$id, $email, $courseName, $completedratio, $lastactivity, $provider = $field.split('|')
$course = [OnlineCourse]::new($id, $email, $courseName, $completedratio, $lastactivity, $provider)
$list.Add($course)
}
This is slightly adapted from another answer and it worked for me.
$dburl="postgresql://postgres:secret_pwd#database-host:5432/dbname"
$psqlPath = 'C:\Program Files\PostgreSQL\11\bin\psql.exe'
function Query {
param($Sql)
Write-Host $Sql
$rows = $Sql `
| &$psqlPath "-A" $dburl | ConvertFrom-Csv -Delimiter '|'
$result = #($rows | Select-Object -SkipLast 1)
Write-Host "-> " (ConvertTo-Json $result)
$result
}
$rows = Query "select ... from ..."