I have a file which will have full path of files. For example:
servername\xyz\abc.txt
servername\pqr\ab1.txt
I need to get only file name (abc.txt and ab1.txt) using PowerShell.
Instead of using the resources getting the file you can use Split-Path on each line item. -Leaf is the switch needed to return just the file name.
PS M:\Scripts> split-path "servername\pqr\ab1.txt" -Leaf
ab1.txt
If you had this information in a file you could iterate through all the entires
$fileName = Get-Content fullfilepaths.txt | ForEach-Object{split-path $_ -Leaf}
Another
A simple one that would also work ( Not sure if the performance is different ) would be to use split and return the last element.
("servername\pqr\ab1.txt".Split("\"))[-1]
PSH$ $file = Get-ChildItem "servername\pqr\ab1.txt"
PSH$ $file.Name
PSH$ $file.Name
should return ab1.txt
Related
I have a file that follows this naming convention: project.customer.version-number.zip
So for example i might have a file called: project.customer.1.1.889.zip
The "version-number" will change.
"project" and "customer" will stay the same. The zip file extension will always be the same.
I long way to get it I have found is to use multiple Split paths and then concatenate together to get the full version number. So i would have:
$1 = (Split-Path -Path $filePath -Leaf).Split(".")[2];
$2 = (Split-Path -Path $filePath -Leaf).Split(".")[3];
$3 = (Split-Path -Path $filePath -Leaf).Split(".")[4];
$version = $1 + "." + $2 "." + $3
Is there a quicker / better way to extract just the version number (i.e. the 1.1.889) if i don't know what it will be every time with powershell?
You can limit the number of item that split returns. In this case you just want to split it into Project, Customer, and Version. First we'll reduce it to just the file name with Split-Path -leaf, then we remove the file extension with -replace, and then we'll split the remaining file base name 3 times.
$project,$customer,$version = ((Split-Path -Path $filePath -Leaf) -replace '\.zip$').Split(".",3)
How to get the 4th folder name and store it in a variable while looping through the files stored in a parent folder. For example, if the path is
C:\ParentFolder\Subfolder1\subfolder2\subfolder3\file.extension
C:\ParentFolder\Subfolder1\subfolder2\subfolder4\file.extension
C:\ParentFolder\Subfolder1\subfolder2\subfolder5\file.extension
then subfolder2 name should be stored in a variable. Can any one please help me on this?
get-childitem $DirectorNane -Recurse | Where-Object{!($_.PSIsContainer)} | % {
$filePath = $_.FullName
#Get file name
$fileName = Split-Path -Path $filePath -Leaf
} $FileI = Split-Path -Path $filePath -Leaf
Thanks in advance!
You can use the -split operator on the $filePath variable to get what you want.
$split = $filePath -split '\\'
$myvar = $split[3]
We use the double backslash to split with, because the first slash escapes the slash character to split the path by. Then, we can reference the part of the path we want in the array that gets generated in the "split" variable.
Additionally, you can solve this with a one liner using the following code:
$myvar = $filepath.split('\')[3]
This would ensure that you're always getting the fourth element in the array, but is a little less flexible since you can't specify what exactly you want based on conditions with additional scripting.
If you are asking how to get the parent directory of the directory containing a file, you can call Split-Path twice. Example:
$filePath = "C:\ParentFolder\Subfolder1\subfolder2\subfolder3\file.extension"
$parentOfParent = Split-Path (Split-Path $filePath)
# $parentOfParent now contains "C:\ParentFolder\Subfolder1\subfolder2"
So I am trying to write quite a simple i thought 4 each. This looks in a directory, lists a bunch of pages and then takes the name, adds it into a error page script for IIS. Will it work?! No...I get errors inconsistently from IIS. Anyone had this issue? Anyone see what i am doing wrong here?...
Directory listing is"
400.htm
401-1.htm
401-2.htm
401-3.htm
401-4.htm
401-5.htm
403-1.htm
403-10.htm
403-11.htm
403-12.htm
403-13.htm
403-14.htm
403-15.htm
403-16.htm
403-17.htm
403-2.htm
403-3.htm
403-4.htm
403-5.htm
403-6.htm
403-7.htm
403-8.htm
403-9.htm
403.htm
404-1.htm
404.htm
405.htm
406.htm
407.htm
410.htm
412.htm
414.htm
500-12.htm
500-13.htm
500-15.htm
500.htm
501.htm
502.htm
htmla.htm
My code is below:
$files = dir D:\iis\errorpages
Foreach ($file in $files)
{
$file = $file -replace "[^0-9]"
Add-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST/Website' -filter "system.webServer/httpErrors" -name "." -value #{statusCode=$file;prefixLanguageFilePath='D:\iis\errorpages';path="$file"}
}
$file in every loop of foreach consists an object with some properties. With your regex line $file = $file -replace "[^0-9]" I assume you want modify the file name. If I assume correctly then you should use:
$fileName = $file.name -replace "[^0-9]"
also this might be wrong:
-value #{statusCode=$file;prefixLanguageFilePath='D:\iis\errorpages';path="$file"
if you want a path and filename use property fullname
if you want a directory where it lives, you need to combine property fullname with string operations. Something like this $file.FullName.Substring(0, $file.FullName.LastIndexOf("\"))
I want to extract filename from below path:
D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv
Now I wrote this code to get filename. This working fine as long as the folder level didn't change. But in case the folder level has been changed, this code need to rewrite. I looking a way to make it more flexible such as the code can always extract filename regardless of the folder level.
($outputFile).split('\')[9].substring(0)
If you are ok with including the extension this should do what you want.
$outputPath = "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv"
$outputFile = Split-Path $outputPath -leaf
Use .net:
[System.IO.Path]::GetFileName("c:\foo.txt") returns foo.txt.
[System.IO.Path]::GetFileNameWithoutExtension("c:\foo.txt") returns foo
Using the BaseName in Get-ChildItem displays the name of the file and and using Name displays the file name with the extension.
$filepath = Get-ChildItem "E:\Test\Basic-English-Grammar-1.pdf"
$filepath.BaseName
Basic-English-Grammar-1
$filepath.Name
Basic-English-Grammar-1.pdf
Find a file using a wildcard and get the filename:
Resolve-Path "Package.1.0.191.*.zip" | Split-Path -leaf
$(Split-Path "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv" -leaf)
Get-ChildItem "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv"
|Select-Object -ExpandProperty Name
You could get the result you want like this.
$file = "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv"
$a = $file.Split("\")
$index = $a.count - 1
$a.GetValue($index)
If you use "Get-ChildItem" to get the "fullname", you could also use "name" to just get the name of the file.
Just to complete the answer above that use .Net.
In this code the path is stored in the %1 argument (which is written in the registry under quote that are escaped: \"%1\" ). To retrieve it, we need the $arg (inbuilt arg). Don't forget the quote around $FilePath.
# Get the File path:
$FilePath = $args
Write-Host "FilePath: " $FilePath
# Get the complete file name:
$file_name_complete = [System.IO.Path]::GetFileName("$FilePath")
Write-Host "fileNameFull :" $file_name_complete
# Get File Name Without Extension:
$fileNameOnly = [System.IO.Path]::GetFileNameWithoutExtension("$FilePath")
Write-Host "fileNameOnly :" $fileNameOnly
# Get the Extension:
$fileExtensionOnly = [System.IO.Path]::GetExtension("$FilePath")
Write-Host "fileExtensionOnly :" $fileExtensionOnly
You can try this:
[System.IO.FileInfo]$path = "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv"
# Returns name and extension
$path.Name
# Returns just name
$path.BaseName
$file = Get-Item -Path "c:/foo/foobar.txt"
$file.Name
Works with both relative and absolute paths
Right up front apologies for my lack of knowledge with Powershell. Very new to the language . I need to copy some files located in a certain path to another similar path. For example:
C:\TEMP\Users\<username1>\Documents\<varyingfoldername>\*
C:\TEMP\Users\<username2>\Documents\<varyingfoldername>\*
C:\TEMP\Users\<username3>\Documents\<varyingfoldername>\*
C:\TEMP\Users\<username4>\Documents\<varyingfoldername>\*
etc....
to
C:\Files\Users\<username1>\Documents\<varyingfoldername>\*
C:\Files\Users\<username2>\Documents\<varyingfoldername>\*
C:\Files\Users\<username3>\Documents\<varyingfoldername>\*
C:\Files\Users\<username4>\Documents\<varyingfoldername>\*
etc....
So basically all files and directories from path one need to be copied to the second path for each one of the different paths. The only known constant is the first part of the path like C:\TEMP\Users...... and the first part of the destination like C:\Files\Users.....
I can get all the different paths and files by using:
gci C:\TEMP\[a-z]*\Documents\[a-z]*\
but I am not sure how to then pass what's found in the wildcards so I can use them when I do the copy. Any help would be appreciated here.
This should work:
Get-ChildItem "C:\TEMP\*\Documents\*" | ForEach-Object {
$old = $_.FullName
$new = $_.FullName.Replace("C:\TEMP\Users\","C:\Files\Users\")
Move-Item $old $new
}
For additional complexity in matching folder levels, something like this should work:
Get-ChildItem "C:\TEMP\*\Documents\*" -File | ForEach-Object {
$old = $_.FullName
$pathArray = $old.Split("\") # Splits the path into an array
$new = [system.String]::Join("\", $pathArray[0..1]) # Creates a starting point, in this case C:\Temp
$new += "\" + $pathArray[4] # Appends another folder level, you can change the index to match the folder you're after
$new += "\" + $pathArray[6] # You can repeat this line to keep matching different folders
Copy-Item -Recurse -Force $old $new
}