How to tell powershell dir command to look a folder up? - windows

The folder structure is:
--root
--root\source-code\
--root\powershell-scripts\
I need the method below that is inside the \powershell-scripts folder to target files inside \source-code:
function Test($param)
{
dir -Include ASourceCodeFile.txt -Recurse |
% { SomeMethod $_ $param }
}
What am I missing?

The $PSScriptRoot automatic variable contains the path of the directory in which the current script is located. Use Split-Path to find its parent (your --root) and Join-Path to get the path to the source-code folder:
Join-Path -Path (Split-Path $PSScriptRoot -Parent) -ChildPath 'source-code'
$PSScriptRoot was introduced in PowerShell 3.0

A bit late, but maybe still helpful for someone:
Directory structure :
MyRoot\script\scriptrunning.ps1
config:
MyRoot\config.xml
to read the xml file from scriptrunning.ps1:
[xml]$Config = Get-Content -path "${PSScriptRoot}\..\config\config.xml"

if you have a script in --root\powershell-scripts\ and you want to reference something in --root\source-code\ or say get-content you can do this:
cd --root\powershell-scripts\
get-content '..\source-code\someFile.txt'
The ..\ references the parent directory which contains \source-code\ and then you reference or pull in file or scripts from that directory.

this was a trick that I used in vbs that I converted to PS...
$scriptPath = Split-Path $MyInvocation.MyCommand.Path -Parent
$a = $scriptPath.split("``\``") for ($i = 0 ; $i -lt $a.count-1 ; $i++){
$parentDir = $parentDir + $a[$i] <br>
if($i -lt $a.count-2){$parentDir = $parentDir + "``\``"}
}
Write-Output $parentDir

Related

Powershell - create directories form files in a dierectory

I am trying to clean up and group files in a directory by creating subdirectories and then copying the files into the new directories.
Example:
test01.a.jpg
test01.a.txt
test01.b.bak
test01.b.txt
test02.a.txt
test02.a.jpg
test02.a.bak
test03.a.txt
test03.a.bak
test03.b.txt
I wish to create subdirectories like test01, test02, test03 and ideally copy the relevant files over. All groups will have a txt file but more or less of the others.
To create the directories I have got as far as
gci -file *.txt | New-Item -ItemType directory $_.name
which doesn't work as expected.
If your files have names like that, you can simply split the filename on the dot and take only the first part as new folder name.
Then test if a subfolder like that already exists (if not create it) and move the file.
Something like this
$sourcePath = 'D:\Test' # put the real path to the files here
# if you want only the files with extension .txt, use filter '*.*.txt'
(Get-ChildItem -Path $sourcePath -File -Filter '*.*.*') | ForEach-Object {
# use the first part of the file name for subdirectory name
$destinationPath = Join-Path -Path $sourcePath -ChildPath $_.Name.Split(".")[0]
if (!(Test-Path -Path $destinationPath -PathType Container)) {
# if a subdirectory with that name does not already exist, create it
$null = New-Item -Path $destinationPath -ItemType Directory
}
# now move the file to that (new) destination folder
$_ | Move-Item -Destination $destinationPath
}
Actually, algorithm is simple (we don't need to previously compare names of files. All we need is just use a $_.BaseName property)
<#Creating folders and moving files using BaseName property #>
gci *.txt | % { new-item -ItemType Directory -Path ($_.Directory.ToString() + "\" + $_.BaseName.ToString())}
gci -file | % { Move-item $_.Fullname ($_.Directory.ToString() + "\" + $_.BaseName.ToString())}

Move contents of folder (Download) into recycle.bin folder - Powershell [duplicate]

When using the rm command to delete files in Powershell, they are permanently deleted.
Instead of this, I would like to have the deleted item go to the recycle bin, like what happens when files are deleted through the UI.
How can you do this in PowerShell?
2017 answer: use the Recycle module
Install-Module -Name Recycle
Then run:
Remove-ItemSafely file
I like to make an alias called trash for this.
If you don't want to always see the confirmation prompt, use the following:
Add-Type -AssemblyName Microsoft.VisualBasic
[Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile('d:\foo.txt','OnlyErrorDialogs','SendToRecycleBin')
(solution courtesy of Shay Levy)
It works in PowerShell pretty much the same way as Chris Ballance's solution in JScript:
$shell = new-object -comobject "Shell.Application"
$folder = $shell.Namespace("<path to file>")
$item = $folder.ParseName("<name of file>")
$item.InvokeVerb("delete")
Here is a shorter version that reduces a bit of work
$path = "<path to file>"
$shell = new-object -comobject "Shell.Application"
$item = $shell.Namespace(0).ParseName("$path")
$item.InvokeVerb("delete")
Here's an improved function that supports directories as well as files as input:
Add-Type -AssemblyName Microsoft.VisualBasic
function Remove-Item-ToRecycleBin($Path) {
$item = Get-Item -Path $Path -ErrorAction SilentlyContinue
if ($item -eq $null)
{
Write-Error("'{0}' not found" -f $Path)
}
else
{
$fullpath=$item.FullName
Write-Verbose ("Moving '{0}' to the Recycle Bin" -f $fullpath)
if (Test-Path -Path $fullpath -PathType Container)
{
[Microsoft.VisualBasic.FileIO.FileSystem]::DeleteDirectory($fullpath,'OnlyErrorDialogs','SendToRecycleBin')
}
else
{
[Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($fullpath,'OnlyErrorDialogs','SendToRecycleBin')
}
}
}
Remove file to RecycleBin:
Add-Type -AssemblyName Microsoft.VisualBasic
[Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile('e:\test\test.txt','OnlyErrorDialogs','SendToRecycleBin')
Remove folder to RecycleBin:
Add-Type -AssemblyName Microsoft.VisualBasic
[Microsoft.VisualBasic.FileIO.FileSystem]::Deletedirectory('e:\test\testfolder','OnlyErrorDialogs','SendToRecycleBin')
Here's slight mod to sba923s' great answer.
I've changed a few things like the parameter passing and added a -WhatIf to test the deletion for the file or directory.
function Remove-ItemToRecycleBin {
Param
(
[Parameter(Mandatory = $true, HelpMessage = 'Directory path of file path for deletion.')]
[String]$LiteralPath,
[Parameter(Mandatory = $false, HelpMessage = 'Switch for allowing the user to test the deletion first.')]
[Switch]$WhatIf
)
Add-Type -AssemblyName Microsoft.VisualBasic
$item = Get-Item -LiteralPath $LiteralPath -ErrorAction SilentlyContinue
if ($item -eq $null) {
Write-Error("'{0}' not found" -f $LiteralPath)
}
else {
$fullpath = $item.FullName
if (Test-Path -LiteralPath $fullpath -PathType Container) {
if (!$WhatIf) {
Write-Verbose ("Moving '{0}' folder to the Recycle Bin" -f $fullpath)
[Microsoft.VisualBasic.FileIO.FileSystem]::DeleteDirectory($fullpath,'OnlyErrorDialogs','SendToRecycleBin')
}
else {
Write-Host "Testing deletion of folder: $fullpath"
}
}
else {
if (!$WhatIf) {
Write-Verbose ("Moving '{0}' file to the Recycle Bin" -f $fullpath)
[Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($fullpath,'OnlyErrorDialogs','SendToRecycleBin')
}
else {
Write-Host "Testing deletion of file: $fullpath"
}
}
}
}
$tempFile = [Environment]::GetFolderPath("Desktop") + "\deletion test.txt"
"stuff" | Out-File -FilePath $tempFile
$fileToDelete = $tempFile
Start-Sleep -Seconds 2 # Just here for you to see the file getting created before deletion.
# Tests the deletion of the folder or directory.
Remove-ItemToRecycleBin -WhatIf -LiteralPath $fileToDelete
# PS> Testing deletion of file: C:\Users\username\Desktop\deletion test.txt
# Actually deletes the file or directory.
# Remove-ItemToRecycleBin -LiteralPath $fileToDelete
Here is a complete solution that can be added to your user profile to make 'rm' send files to the Recycle Bin. In my limited testing, it handles relative paths better than the previous solutions.
Add-Type -AssemblyName Microsoft.VisualBasic
function Remove-Item-toRecycle($item) {
Get-Item -Path $item | %{ $fullpath = $_.FullName}
[Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($fullpath,'OnlyErrorDialogs','SendToRecycleBin')
}
Set-Alias rm Remove-Item-toRecycle -Option AllScope

Folder deleting after script ends

I am currently writing a script that takes a folder of files, moves the first file to a folder with a specific name, then move the rest to another folder with a number for a name.
My script works however it also moves the folder and renames it too. Which section of the code is causing this?
$path = "C:\Users\User1\Desktop\MergeTest\_First\"
$FileCount = Get-ChildItem -Path $path -File | Measure-Object | %{$_.Count}
$FirstFile = Get-ChildItem -Path $path -Force -File | Select-Object -First 1
$FinalReport = "C:\Users\User1\Desktop\MergeTest\___Final\TestOutput.xlsx"
Move-Item "C:\Users\User1\Desktop\MergeTest\_First\$FirstFile" $FinalReport
$Counter = 0;
Write-host $FileCount
for($Counter = 0; $Counter -lt $FileCount; $Counter++)
{
$FileInWork = Get-ChildItem -Path $path -Force -File | Select-Object -First 1
move-item "C:\Users\User1\Desktop\MergeTest\_First\$FileInWork" "C:\Users\User1\Desktop\MergeTest\__Second\$Counter.xlsx"
Write-host "File Moved"
}
What you could do is specify the -Include *.txt condition to your move-item commands so it is only to move just .txt, .log, or whatever file type you're moving and leave the folder how it is.
I believe your code could do with some cleaning up. Now you are executing Get-ChildItem 3 times, where using it once is enough.
Also, you should try and use the Join-Path rather than constructing the path and filenames yourself.
Especially where you do "C:\Users\User1\Desktop\MergeTest\_First\$FileInWork", you should realize that Get-ChildItem returns FileInfo and/or DirectoryInfo objects; not strings.
Anyway, the below code should do what you want:
# define the path where all other paths are in
$rootPath = "C:\Users\User1\Desktop\MergeTest"
# create the working paths using the common root folder path
$filesPath = Join-Path -Path $rootPath -ChildPath '_First'
$firstDestination = Join-Path -Path $rootPath -ChildPath '___Final'
$secondDestination = Join-Path -Path $rootPath -ChildPath '__Second'
# test if the destination folders exist and if not create them
if (!(Test-Path -Path $firstDestination -PathType Container)) {
Write-Host "Creating folder '$firstDestination'"
$null = New-Item -Path $firstDestination -ItemType Directory
}
if (!(Test-Path -Path $secondDestination -PathType Container)) {
Write-Host "Creating folder '$secondDestination'"
$null = New-Item -Path $secondDestination -ItemType Directory
}
# get an array of all FileInfo objects in $filesPath
# you could consider adding -Filter '*.xlsx' here..
$allFiles = Get-ChildItem -Path $filesPath -Force -File
Write-Host 'Total number of files found: {0}' -f $allFiles.Count
# move the files
for ($i = 0; $i -lt $allFiles.Count; $i++) {
if ($i -eq 0) {
# the first file should go in the $firstDestination folder with specified name
$target = Join-Path -Path $firstDestination -ChildPath 'TestOutput.xlsx'
}
else {
# all other files go to the $secondDestination folder
# each file should have the index number as name
$target = Join-Path -Path $secondDestination -ChildPath ('{0}.xlsx' -f ($i + 1))
}
$allFiles[$i] | Move-Item -Destination $target -Force -WhatIf
}
Hope that helps
Remove the -WhatIf if you are satisfied with whatever the output on console shows.
P.S. I really think you should edit your question and change its title, because nothing in the question has to do with Folder deleting after script ends..

Rename or Remove Characters From a Filename with PowerShell

I am trying to rename or remove part of a filename. I have a scheduled job that moves an updated file from one server to another. Once the file is moved it need to be renamed. For example: Filename_01-23-AB.exe to Filename.exe I want to remove everything from the "_" to the "." and leave the extension intact. I found the following code that should do this but I can't seem to get it to work. Am I headed down the right path here?
## Removes the build number from the filename of "Filename_XX-XX-XX.exe" leaving the new filename to be "Filename.exe" ##
$File = -Path "C:\Temp\TestPath\"
foreach ($File in gci *.exe) {
$Fname = ($File.name).split('.')[0] ## item before the '.' ##
$Prefix = $Fname.split('_')[0] ## item before the '_' ##
$Newname = $Prefix + '.exe'
Rename-Item $file $Newname
}
I've tried simplifying what you're tying to do:
pushd "C:\Temp\TestPath\"
dir | ? { $_.Name -like "*.exe" } |
% { Rename-Item $_ "$($_.BaseName.split('_')[0])$($_.Extension)" }
popd
First, this changes the directory your PowerShell is looking at to your defined directory (pushd).
Then it will get the contents of your directory, find all objects with the extension of .exe, and split the file's base name at the underscore. popd will then set the directory back to where-ever it was previous to running this script.
I think this can be simplifyed even more using a regex to remove everything between the first underscore and the file extension:
$Path= 'C:\Temp\TestPath\'
Get-ChildItem $Path -Filter "*_*.exe" | foreach {
$_ | Rename-Item -NewName ($_.Name -replace '(?=_).+(?=\.)')
}
This also works when the filename doesn't contain an underscore.
And here the regex demo.
!not tested
try this
$path = 'C:\Temp\TestPath\'
gci $path *.exe | ? basename -match '_' | % {
# if the file.txt already exists, rename it to file-1.txt and so on
$num = 1
$base = $_.basename.substring(0, $_.basename.indexof('_'))
$ext = $_.extension
$dir = $_.directory
$newname = Join-Path $dir "$base$ext"
while (Test-Path $newname) {
$newname = Join-Path $dir "$base-$num$ext"
$num++
}
# finally, rename the file
ren $_.fullname $newname
}

How to list files with a for loop?

How I can do a ls using PowerShell?
for i in `ls`
do
if [ -d $i ] #miro si és directori
then
echo "Directory"
else echo "File"
fi
done
POWERSHELL
$llistat -ls
forEach $element in $llistat ??? this is possible
}
A more PoSh way is to use a pipeline, and perhaps a hashtable:
$type = #{
$true = 'Directory'
$false = 'File'
}
Get-ChildItem | ForEach-Object { $type[$_.PSIsContainer] }
PowerShell even has a default alias ls for Get-ChildItem, so you could use more Unix-ish syntax:
ls | % { $type[$_.PSIsContainer] }
In PowerShell, the Get-ChildItem cmdlet works like ls (at least with the file system provider). All items returned have a PowerShell-specific property called PSIsContainer, indicating whether it's a directory or not:
foreach($item in (Get-ChildItem)){
if($item.PSIsContainer){
"Directory"
} else {
"File"
}
}
If you want to see what's inside each directory, one level down:
foreach($item in (Get-ChildItem)){
if($item.PSIsContainer){
# Directory! Let's see what's inside:
Get-ChildItem -Path $item.FullName
}
}
As of PowerShell version 3.0 and up, the Get-ChildItem supports a File and Directory switch on the filesystem provider, so if you ONLY want directories, you could do:
Get-ChildItem -Directory
So the second example becomes:
Get-ChildItem -Directory | Get-ChildItem
You could also list files recursively (like ls -R):
Get-ChildItem -Recurse

Resources