How to get the name of a directory by regex? - windows

I need to get the path or name of a directory, the things I know about it:
- the folder the directory is on
- its name follows a given regex
How can I accomplish this?
Working on Jenkins pipeline (groovy)

You can apply the pwd pipeline step to return the current directory as String and fetch the name from it by using regex groups.
See the following example to extract values from regex using groovy: https://gist.github.com/EwanDawson/2407215

I ended up assigning the result of powershell to the variable, I did this by telling the powershell step that it has a stdout return like:
def folder = powershell (returnStdout: true, script: """
Get-ChildItem -directory | Select-String -pattern '<pattern>'
""")
That combined with pwd() gives me the full path, although you can also get full path using a pipeline in the command, something like Get-ChildItem -directory | Select-Object Fullname | Select-String -pattern '<pattern>'

Related

Attempting to search and replace a few lines in an XML file in every user's appdata/roaming folder

I'm still kind of new to windows administration and very new to powershell so please forgive my ignorance. I wrote the following one-liner and I'm attempting to adapt it so that it can modify every existing user's FTRSettings.xml file on a PC. I'm worried that using the following path with a wildcard in place of the username would only replace the first file it finds.
C:\users\*\appdata\Roaming\FTR\GoldMain\FTRSettings.xml
Tested and working one liner executed from the appdata\Roaming\FTR\GoldMain\ directory.
((Get-Content -Path .\FTRSettings.xml -Raw) -replace '<Setting name="audioLevelsVisible" type="11">0</Setting>','<Setting name="audioLevelsVisible" type="11">-1</Setting>' -replace '<Setting name="inputLevelsVisible" type="11">0</Setting>','<Setting name="inputLevelsVisible" type="11">-1</Setting>' -replace '<Setting name="logSheetPaneViewState" type="11">0</Setting>','<Setting name="logSheetPaneViewState" type="11">-1</Setting>')
I was wondering if anyone could point me in the right direction.
To process each file individually:
Use Get-ChildItem with your wildcard-based path to find all matching files.
Loop over all matching files with ForEach-Object and perform the string replacement and updating for each file.
Note: I'm using a single -replace operation for brevity.
Get-ChildItem -Path C:\users\*\appdata\Roaming\FTR\GoldMain\FTRSettings.xml |
ForEach-Object {
$file = $_
($file | Get-Content -Raw) -replace 'foo', 'bar' |
Set-Content -Encoding utf8 -LiteralPath $file.FullName -WhatIf
}
Note: The -WhatIf common parameter in the command above previews the operation. Remove -WhatIf once you're sure the operation will do what you want.
Note the use of -Encoding to control the character encoding explicitly, because the original encoding is never preserved in PowerShell; instead, the cmdlet's own default applies - adjust as needed.

Get formatted output of file details in a folder

I want to retrieve certain details about all files in a given folder.
Get-ItemPropertyValue .\*.dll -name versioninfo
Gives me output like this:
That aint bad but i wanna include some other properties, and the -include switch doesnt work like i thought.
And giving it -name versioninfo, lastwritetime for example, doesnt add another column to the list, it prints the date underneath:
How can i bring all read properties of one file into the same row (add column)?
EDIT:
i am aware of format-list but its not giving me the wide list output and format-wide only accepts one single property...
How about this?
Get-Item .\*.dll | Select-Object `
#{N='ProductVersion';E={Get-ItemPropertyValue $_ -Name versionInfo | Select-Object -ExpandProperty ProductVersion}} `
,#{N='FileVersion';E={Get-ItemPropertyValue $_ -Name versionInfo | Select-Object -ExpandProperty FileVersion}} `
,Name `
,LastWriteTime
I found an easier, more readable way to do this, and still generate the output when run inside a script:
Get-Childitem .\ThirdPartyComponents\*.dll | select name, lastwritetime, #{l="ProductVersion";e={$_.VersionInfo.ProductVersion}}, #{l="FileVersion";e={$_.VersionInfo.FileVersion}} | ft
The last pipe to | ft (Format table) is needed because the command does not generate any output when run inside a script otherwise. Why that is, im not exactly sure..

Powershell "LastWriteTime" not working

Is there a way to stop Powershell from sorting by default? I need to read in files from a directory and in the order which they are listed in the directory I need them to also be listed in the array (variable). Even when I use -lastwritetime on the get-childitem command, it seems to have no affect. The primary reason why I want to do this is because the files have names that are all the same except each file has a number after it like the following:
document1.doc
document2.doc
document3.doc
.....
document110.doc
The problem is if it's sorted by name, it will sort in this manner:
document1.doc
document10.doc
document111.doc
Which is horribly wrong!
Right now I have this command and it doesn't work:
$filesnames1 = get-childItem -name *.doc -Path c:\fileFolder\test | sort-object -LastWriteTime
You probably want something more along these lines.
$filesnames1 = Get-ChildItem -Path c:\fileFolder\test\*.doc |
Sort-Object -Property LastWriteTime
I don't think either of those two cmdlets have a -LastWriteTime parameter.
If you need only the names from those filesystem objects, you can use ($filesnames1).Name after the code above. There are other ways.
Thanks for responding Mike. What I did is put a "-filter *.pdf" just before -path which gave me the headers. Then I piped in a "select-object -ExpandProperty name" to list it exactly how I needed it to. It was a little trial and error but I did eventually figure it out.
$filesnames1 = Get-ChildItem -filter *.doc -Path c:\fileFolder\test |
Sort-Object -LastWriteTime | -ExpandProperty name

Powershell renaming special directories recursively

I got this folder structure
C:\Users\myUser\Desktop
including folders called
BL-100
BL-105
BL-108
and so on...
most BL-folders storing a file.xml, but not all.
So on Desktop are much folders starting with BL- and the most, but not all, storing a file.xml.
Now I want to search all folders which are starting with BL- and store a file.xml and rename those folders to RG-100, RG-105, RG-108 and so on
At the moment I got this script:
foreach($Directory in Get-ChildItem -Path C:\Users\myUser\Desktop -Recurse | Where-Object{($_.Name.Substring(0,3) -eq 'BL-')}){
}
This does not work and is showing me error: Exception calling "Substring" with "2" argument(s): "Index and length must refer to a location within the string. Parameter name: length"
Anyone can help please?
The error you're seeing is because SubString fails for some reason. The most likely reason would be if the string is not long enough; e.g. if you had a folder with a 1 character long name. To see what I mean, try running: '1'.Substring(0,2).
To avoid this, instead you could use the like operator. e.g.
foreach($Directory in (
Get-ChildItem -LiteralPath 'C:\Users\myUser\Desktop' -Recurse `
| Where-Object{($_.Name -like 'BL-*')}
)){
#...
}
Just do it:
Get-ChildItem "C:\Users\myuser\Desktop" -directory -Filter "BL-*"

Load file file with PowerShell?

I would like to load a file, contains vars' statements.
For example, VLANS.conf will contain $VLANS = "VLAN1500", "VLAN877"
How do I load it into powershell?
Read the file content and use the Invoke-Expression cmdlet to evaluate each line as an expression:
PS > Get-Content .\VLANS.conf | Foreach-Object {Invoke-Expression $_}
PS >$VLANS
VLAN1500
VLAN877
Alternative is to have a VLANS.ps1 or VLANS.conf.ps1 or something and "dot source the file"?
. .\VLANS.ps1
You will have the advantage of having here-strings, script blocks ( and of course anything you can have in a powershell script)

Resources