About
File (System, Transfer, Storage) in Powershell
Articles Related
Management
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
Traverse
Tree
- finds all .jpg files in the current user's directories
get-childitem -path $env:userprofile\* -include *.jpg -recurse
One level
Get-ChildItem $sourceDir -Filter *.zip |
Foreach-Object {
echo $_.FullName
}
where:
Filter
$JDK_HOME=Get-ChildItem $JAVA_HOME -Filter 'jdk*' | %{$_.FullName}
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
Current Location
$loc = Get-Location
$loc = $pwd
- As argument
${PWD}
Rename
rename-item –path '.\.htaccess.dist' -newname '.\.htaccess'
Exist
if (Test-Path $path) { ... }
if (-not (Test-Path $path)) { ... }
if (!(Test-Path $path)) { ... }
Remove
Remove-Item -Recurse -Force some_dir
Copy File
Copy-Item "C:\Wabash\Logfiles\mar1604.log.txt" -Destination "C:\Presentation"
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
Is File or dir
if(Test-Path $_ -pathType container){"Folder"}
if(Test-Path $_ -pathType leaf){"File"}
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"
}