PowerShell - File System

1 - About

3 - Management

3.1 - Get name and extension

  • From the file system
dir *.* | select BaseName,Extension
  • From a variable (with the GetFileNameWithoutExtension and GetExtension static methods from the System.IO.Path class)
$filePath="c:\hello\nico.txt"
[System.IO.Path]::GetFileNameWithoutExtension($filePath)
[System.IO.Path]::GetExtension($filePath)
nico
txt

3.2 - Traverse

3.2.1 - Tree

  • finds all .jpg files in the current user's directories
get-childitem -path $env:userprofile\* -include *.jpg -recurse

3.2.2 - One level

Get-ChildItem $sourceDir -Filter *.zip | 
Foreach-Object {
   echo $_.FullName
}

where:

3.2.3 - Filter

$JDK_HOME=Get-ChildItem $JAVA_HOME -Filter 'jdk*' | %{$_.FullName}

3.3 - Create

  • a file in the current directory
New-Item fileName.ext 
# in a dir with content
New-Item -Path C:\path -Name "testfile1.txt" -ItemType "file" -Value "This is a text string."
  • A directory
New-Item -ItemType Directory -Force -Path C:\Whatever | Out-Null
# out-Null to discard the output

3.4 - Current Location

$loc = Get-Location
$loc = $pwd

See managing-current-location

3.5 - Rename

rename-item –path '.\.htaccess.dist' -newname '.\.htaccess'

3.6 - Exist

if (Test-Path $path) { ... }
if (-not (Test-Path $path)) { ... }
if (!(Test-Path $path)) { ... }

3.7 - Remove

Remove-Item -Recurse -Force some_dir

3.8 - Copy File

Copy-Item "C:\Wabash\Logfiles\mar1604.log.txt" -Destination "C:\Presentation"

3.9 - Content

  • Get-Content (alias: gc): Help to read a text file
$content = Get-Content $path
# or
$Computers = Get-Content -Path C:\temp\DomainMembers.txt
# $Computers is now an array containing a computer name in each element.
  • Filter Content
gc log.txt | select -first 10 # head
gc log.txt | select -last 10  # tail
gc log.txt | more             # or less if you have it installed
gc log.txt | %{ $_ -replace '\d+', '($0)' }         # sed
gc log.txt | %{ ($_ -split '\s+')[3] }   # Get the 4th element separated by space
  • Set-Content: add content to a file (See out-file to overwrite)
# filter and save content to a new file 
$content | Where-Object {$_ -match 'whatever'} | Set-Content ($_.BaseName + '_out.txt')
 
# Create a powershell script conf with carriage return
$CONTENT="`$ORACLE_DB_PWD='$installPwd'`r`n`$WEBLOGIC_PWD='$installPwd'`r`n`$ORACLE_DB_SCHEMA_PWD='$installPwd'"
$CONTENT | Set-Content $PWD_FILE
  • Out-File: Overwrite the content of a file

3.10 - Is File or dir

if(Test-Path $_ -pathType container){"Folder"}
if(Test-Path $_ -pathType leaf){"File"}

3.11 - Path

  • Verify that a command is in the path
if ((Get-Command "git.exe" -ErrorAction SilentlyContinue) -eq $null) 
{ 
   Write-Host "Unable to find git.exe in your PATH"
}

4 - Documentation / Reference

lang/ps/fs.txt · Last modified: 2018/09/26 11:36 by gerardnico