How can I split the result of powershell select-string command? - powershell

I have a command like this:
powershell -command "Select-String -Path 'C:\Program Files\Zabbix Agent 2\zabbix_agent2.conf' -Pattern 'ServerActive'"
Which outputs:
C:\Program Files\Zabbix Agent 2\zabbix_agent2.conf:5:ServerActive=79.240.122.98
I want to get the "79.240.122.98" part. How can I do that? I think that the best approach would be to split the string by the "=" character and then get the second item, but I did not find the way to do it.

From a .bat file? This works for me.
powershell ((select-string serveractive 'c:\program files\zabbix agent 2\zabbix_agent2.conf') -split '=')[1]
79.240.122.98

Related

File path with spaces not working in batch file

I am trying to cat a text file containing a PowerShell script from a .bat file into PowerShell running within the command line.
It's kind of a workaround to start a PowerShell script on startup without having permission on the system.
It works perfectly fine until I try paths with spaces. Does someone know how to make this work?
I searched and tried many solutions (see 3,4,5,6) but either this is a very specific case, or I am doing something wrong. My knowledge of scripts in general is lacking some, but I'm trying my best. Please use simple language in your answer.
This works
#echo off
powershell "cat -raw C:\examplenospace\test.txt | invoke-expression"
This works
#echo off
set "file=C:\examplenospace\test.txt"
powershell "cat -raw %file% | invoke-expression"
Not working
#echo off
set "file=C:\example with space\test.txt"
powershell "cat -raw %file% | invoke-expression"
This also doesn't work of course
#echo off
powershell "cat -raw "C:\example with space\test.txt" | invoke-expression"
Also doesn't work
#echo off
powershell ""cat -raw "C:\example with space\test.txt" | invoke-expression"
I tried many variations, nothing seems to work
#echo off
powershell "cat -raw \"\"C:\example with space\test.txt" | invoke-expression"
How can I make it work?
#Compo thank your for your answer, this worked straight away, both of them!
#%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -Command "Get-Content -LiteralPath 'C:\example with space\test.txt' -Raw | Invoke-Expression"
#%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -Command "Get-Content -LiteralPath "C:\example with space\test.txt" -Raw | Invoke-Expression"

Powershell looping through files to pass to a program as a parameter

I have the following two cmd.exe commands, but I need to convert them to Powershell, and I've failed miserably trying to figure it out. Line 1 is finding a dll, but only when in a bin folder and line two then takes all the entries it finds and runs a command with it, e.g. bin\Debug\file, bin\Release\file
Can anyone help? The only limitation is this is inside a yaml runner file so I don't think I can split lines for each part, e.g. I don't think a Foreach-Object will work.
dir /s /b RunnerUnitTest.dll | findstr /r bin\\ > tests_list.txt
for /f %f in (tests_list.txt) do vstest.console.exe "%f"
I got as far as this
(gci -r RunnerUnitTest.dll).FullName | select-string bin
thanks.
Write a multi-line powershell script to do the work and then call that script from your yaml runner.
powershell -file "c:\myscripts\runtests.ps1" "c:\mydlls\RunnerUnitTest.dll" "c:\mytests\tests_list.txt"
A single command (pipeline), spread across 3 lines for readability, using built-in command aliases for brevity (but the parameter names are spelled out, for long-term robustness):
gci -Recurse -Filter RunnerUnitTest.dll |
? FullName -match bin\\ |
% { vstest.console.exe $_.FullName }
gci -Recurse -Filter RunnerUnitTest.dll finds all RunnerUnitTest.dll in the current directory's subtree; -Filter makes for faster matching than using the (positionally implied) -Path parameter.
? FullName -match bin\\ uses ? (Where-Object) to test the .FullName (full path) property values of the input file-info objects for matching regex bin\\, i.e. for a literal bin\ substring, and only passes matching file-info objects on.
% { vstest.console.exe $_.FullName } uses % (ForEach-Object) to invoke vstest.console.exe with each matching file's full path.
Note that no intermediate file with a list of DLLs to process is created, because it isn't necessary.
If you need to pass the above to an explicit invocation of the PowerShell CLI, you'd do:
powershell -noprofile -command "gci -Recurse -Filter RunnerUnitTest.dll | ? FullName -match bin\\ | % { vstest.console.exe $_.FullName }"
If you're using PowerShell [Core] 6+, substitute pwsh for powershell.

Get-Content - cannot find path error in windows command prompt

I was trying to execute powershell script from Cmd.
C:\powershell C:\Powershell_Scripts\CheckWebSiteExists.ps1
Error : Get-Content : Cannot find path '\\XXXX\China-team\Release
Package\CustomerDB_file\CustomerDB.txt' because it does not
exist.
Powershell script :
$test = (Get-Content "\\XXXX\China-team\Release Package\\CustomerDB_file\CustomerDB.txt") -split ','
this was running fine in powershell but not in cmd. I have mapped that share path and tried executing, but no luck.
Try This..
powershell -command "$test = (Get-Content "\\XXXX\China-team\Release Package\\CustomerDB_file\CustomerDB.txt") -split ','"
It appears that PowerShell cannot find the filename you have specified. Take a step back and verify that the file is there.
Test-Path '\\XXXX\China-team\Release Package\\CustomerDB_file\CustomerDB.txt'
If that does not return True, try removing the escaped backslash.
Test-Path '\\XXXX\China-team\Release Package\CustomerDB_file\CustomerDB.txt'
If Test-Path cannot return True, then the file cannot be found. There is no point in using Get-Content until the file can be found.

Set Location in PowerShell that contains a ampersand (&)

How do i set my directory using PowerShell to the below location ?
W:\B&M\Store Segmentation\Pete\Python
I tried using:
PS > Set-Location -Path W:\B"&"M\Store Segmentation\Pete\Python
While using " or ' is totally a better idea, but should be informed of PowerShell escape character:
`
Using this caracher, you can scape special characters, for example:
Set-Location C:\A`&B
You need it for example in cases that the folder name contains []:
Set-Location 'C:\A&B[1]' # Will Fail
Set-Location 'C:\A&B`[1`]' # Correct
Use " double quotes or ' apostrophes as follows:
Set-Location -Path "W:\B&M\Store Segmentation\Pete\Python"
or
Set-Location -Path 'W:\B&M\Store Segmentation\Pete\Python'
Read About Quoting Rules for explanation.

Script to replace line that contains text

I found another discussion on this, where there were numerous different options available but most of them didn't seem to work for myself or the original poster. I did however find an example that is confirmed working, however I am struggling with getting it to work and hoping for help.
I need to find a line that begins with "ServerName=" and replace this with my own line. I have used the example that was found and modified it, but I am getting errors when using it.
PowerShell Command:
powershell -Command "(Get-Content 'KFGame\Config\PCServer-KFGame.ini') | Foreach-Object {$_ -replace '^ServerName.$', ('ServerName=Network BUF 12345 Normal')} | Set-Content 'KFGame\Config\PCServer-KFGame.ini'"
Error Message:
) was unexpected at this time
If you want to run complex PowerShell statements from CMD you need to put them in quotes so that CMD just sees a string and doesn't try to handle special characters (like pipes):
powershell -Command "(Get-Content 'C:\Host400.txt') | Foreach-Object {$_ -replace '^workstationID.*$', (""WorkstationID=$computerName""} | Set-Content 'C:\Host400.txt'"
Note that you need to either escape or replace double quotes within the command string.
A better approach is to put the PowerShell statement(s) into a .ps1 script and run that via the -File parameter:
powershell -File "C:\path\to\your.ps1"