PowerShell - Test-Path ignoring file name - powershell

How can you use Test-Path (or any other function) to test if a folder exists - ignoring any trailing file names?
I need this to test if the target folder exists in order to write an output file to it. My script accepts a "full path" parameter like "C:\Temp\myexport.csv", and I only need to know that C:\Temp exists in order to be able to create the file.
Thank you

try this :
$OutFile = "C:\Temp\myexport.csv"
$Dir=[System.IO.Path]::GetDirectoryName($OutFile)
if(!(Test-Path $Dir)) {
Write-Host "Invalid path"
}

Nevermind.. I didn't Google hard enough:
$OutFile = "C:\Temp\myexport.csv"
if(!Test-Path -Path (Split-Path -Path $OutFile)) {
Write-Host "Invalid path"
}

Related

Powershell - Get path location via Find-Path Function

So i wrote the code below
$datum_vandaag = $(Get-Date).toString('yyyy-MM-dd')
$maand = $datum_vandaag.substring(5, 2)
if (-Not (Test-Path -Path "C:\Users\Nick\Desktop\ITIL\**" -Include *$maand*)) { #(contains words gelijk aan (get-date)
md -Path "C:\Users\Nick\Desktop\ITIL\[??????]\$datum_vandaag" # Makes folder with name of current date in path:
}
Else{Write-Output "test output"
}
The IF function is looking if in the path Desktop\ITIL** there is a folder that has the same number as the current date (07 is july) somewhere in the name of the folder.
Now i would like to make a new folder in the folder that is found by the command below :
Test-Path -Path "C:\Users\Nick\Desktop\ITIL\**" -Include *$maand*
How could i get acces to this path so i can use it in the md command (now marked with [??????] in the code) Because currently i only receive if a folder is found, false or true.
All i could find what possibly would work is get-path or resolve-path but I don't know how to implement this.
It's difficult to fully understand what you are asking, but I think the command you are looking for is Get-Item which will return an object to the named folder.
Something like this might work:
$path = Get-Item -Path "C:\Users\Nick\Desktop\ITIL\**" -Include *$maand*
if ($path) {
$newPath = Join-Path -Path $path -ChildPath $datum_vandaag
New-Item -Path $newPath -ItemType Directory
}

In Powershell, how do I copy/paste a file, if file already exists, to roll the new copy of the file?

I am running a powershell script, with the following
Copy-Item -Path c:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG\machine.config -Destination c:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG\machine.orig
If the machine.orig already exists, how can i make it copy it to machine.orig1, and if that already exists, machine.orgin2?
If I may make a suggestion. Personally, I like the idea of a date/time stamp on the file rather than an incremental number. This way you know when the file was backed up, and you're far less likely to run into confusion over the file. Plus the script code is simpler.
Hope this helps.
$TimeStamp = get-date -f "MMddyyyyHHmmss"
$SourceFile = Dir c:\folder\file.txt
$DestinationFile = "{0}\{1}_{2}.{3}" -f $SourceFile.DirectoryName, $SourceFile.BaseName, $TimeStamp, $SourceFile.Extension
copy-Item $sourcefile $DestinationFile
#let us first define the destination path
$path = "R:\WorkindDirectory"
#name of the file
$file = "machine.orgin"
#let us list the number of the files which are similar to the $file that you are trying to create
$list = Get-ChildItem $path | select name | where name -match $file
#let us count the number of files which match the name $file
$a = ($list.name).count
#if such count of the files matching $file is less than 0 (which means such file dont exist)
if ($a -lt 1)
{
New-Item -Path $path -ItemType file -Name machine.orgin
}
#if such count of the files matching $file is greater than 0 (which means such/similar file exists)
if ($a -gt 0)
{
$file = $file+$a
New-Item -Path $path -ItemType file -Name $file
}
Note: This works assuming that the names of the files are in series. Let us say using this script you create
machine.orgin
machine.orgin1
machine.orgin2
machine.orgin3
and later delete machine.orgin2 and re run the same script then it won't work.
Here i have given an example where i have tried to create a new file and you can safely modify the same to copy such file using copy-item instead of new-item

How many ways to check if a script was "successful" by using Powershell?

I am still very new and I have for example one script to backup some folders by zipping and copying them to a newly created folder.
Now I want to know if the zip and copy process was successful, by successful i mean if my computer zipped and copied it. I don't want to check the content, so I assume that my script took the right folders and zipped them.
Here is my script :
$backupversion = "1.65"
# declare variables for zip
$folder = "C:\com\services" , "C:\com\www"
$destPath = "C:\com\backup\$backupversion\"
# Create Folder for the zipped services
New-Item -ItemType directory -Path "$destPath"
#Define zip function
function create-7zip{
param([String] $folder,
[String] $destinationFilePath)
write-host $folder $destinationFilePath
[string]$pathToZipExe = "C:\Program Files (x86)\7-Zip\7zG.exe";
[Array]$arguments = "a", "-tzip", "$destinationFilePath", "$folder";
& $pathToZipExe $arguments;
}
Get-ChildItem $folder | ? { $_.PSIsContainer} | % {
write-host $_.BaseName $_.Name;
$dest= [System.String]::Concat($destPath,$_.Name,".zip");
(create-7zip $_.FullName $dest)
}
Now I can either check if in the parentfolder is a newly created folder by time.
Or i can check if there are zip folders in my subfolders I created.
What way would you suggest? I probably just know this ways, but there are a million way to do this.
Whats your idea? The only rule is , that powershell should be used.
thanks in advance
You could try using the Try and Catch method by wrapping the (create-7zip $_.FullName $dest) with a try and then catch any errors:
Try{ (create-7zip $_.FullName $dest) }
Catch{ Write-Host $error[0] }
This will Try the function create-7zip and write any the errors that many accrue to the shell.
One thing that can be tried is checking the $? variable for the status of the command.
$? stores the status of the last command run,
So for
create-7zip $_.FullName $dest
If you then echo out $? you will see either true or false.
Another option is the $error variable
You can also combine these in all sorts of ways (Or with the exception handling).
For example, run your command
foreach-object {
create-7zip $_.FullName $dest
if (!$?) {"$_.FullName $ErrorVariable" | out-file Errors.txt}
}
That script is more pseudocode for ideas than working code, but it should at least get you close to using it!

Create directory if it does not exist

I am writing a PowerShell script to create several directories if they do not exist.
The filesystem looks similar to this
D:\
D:\TopDirec\SubDirec\Project1\Revision1\Reports\
D:\TopDirec\SubDirec\Project2\Revision1\
D:\TopDirec\SubDirec\Project3\Revision1\
Each project folder has multiple revisions.
Each revision folder needs a Reports folder.
Some of the "revisions" folders already contain a Reports folder; however, most do not.
I need to write a script that runs daily to create these folders for each directory.
I am able to write the script to create a folder, but creating several folders is problematic.
Try the -Force parameter:
New-Item -ItemType Directory -Force -Path C:\Path\That\May\Or\May\Not\Exist
You can use Test-Path -PathType Container to check first.
See the New-Item MSDN help article for more details.
$path = "C:\temp\NewFolder"
If(!(test-path -PathType container $path))
{
New-Item -ItemType Directory -Path $path
}
Test-Path -PathType container checks to see if the path exists and is a directory. When it does not, it will create a new directory. If the path exists but is a file, New-Item will raise an error (you can overwrite the file by using the -force argument if you are risky).
[System.IO.Directory]::CreateDirectory('full path to directory')
This internally checks for directory existence, and creates one, if there is no directory. Just one line and native .NET method working perfectly.
Use:
$path = "C:\temp\"
If (!(test-path $path))
{
md $path
}
The first line creates a variable named $path and assigns it the string value of "C:\temp"
The second line is an If statement which relies on the Test-Path cmdlet to check if the variable $path does not exist. The not exists is qualified using the ! symbol.
Third line: If the path stored in the string above is not found, the code between the curly brackets will be run.
md is the short version of typing out: New-Item -ItemType Directory -Path $path
Note: I have not tested using the -Force parameter with the below to see if there is undesirable behavior if the path already exists.
New-Item -ItemType Directory -Path $path
The following code snippet helps you to create a complete path.
Function GenerateFolder($path) {
$global:foldPath = $null
foreach($foldername in $path.split("\")) {
$global:foldPath += ($foldername+"\")
if (!(Test-Path $global:foldPath)){
New-Item -ItemType Directory -Path $global:foldPath
# Write-Host "$global:foldPath Folder Created Successfully"
}
}
}
The above function split the path you passed to the function and will check each folder whether it exists or not. If it does not exist it will create the respective folder until the target/final folder created.
To call the function, use below statement:
GenerateFolder "H:\Desktop\Nithesh\SrcFolder"
I had the exact same problem. You can use something like this:
$local = Get-Location;
$final_local = "C:\Processing";
if(!$local.Equals("C:\"))
{
cd "C:\";
if((Test-Path $final_local) -eq 0)
{
mkdir $final_local;
cd $final_local;
liga;
}
## If path already exists
## DB Connect
elseif ((Test-Path $final_local) -eq 1)
{
cd $final_local;
echo $final_local;
liga; (function created by you TODO something)
}
}
When you specify the -Force flag, PowerShell will not complain if the folder already exists.
One-liner:
Get-ChildItem D:\TopDirec\SubDirec\Project* | `
%{ Get-ChildItem $_.FullName -Filter Revision* } | `
%{ New-Item -ItemType Directory -Force -Path (Join-Path $_.FullName "Reports") }
BTW, for scheduling the task please check out this link: Scheduling Background Jobs.
There are three ways I know to create a directory using PowerShell:
Method 1: PS C:\> New-Item -ItemType Directory -path "C:\livingston"
Method 2: PS C:\> [system.io.directory]::CreateDirectory("C:\livingston")
Method 3: PS C:\> md "C:\livingston"
From your situation it sounds like you need to create a "Revision#" folder once a day with a "Reports" folder in there. If that's the case, you just need to know what the next revision number is. Write a function that gets the next revision number, Get-NextRevisionNumber. Or you could do something like this:
foreach($Project in (Get-ChildItem "D:\TopDirec" -Directory)){
# Select all the Revision folders from the project folder.
$Revisions = Get-ChildItem "$($Project.Fullname)\Revision*" -Directory
# The next revision number is just going to be one more than the highest number.
# You need to cast the string in the first pipeline to an int so Sort-Object works.
# If you sort it descending the first number will be the biggest so you select that one.
# Once you have the highest revision number you just add one to it.
$NextRevision = ($Revisions.Name | Foreach-Object {[int]$_.Replace('Revision','')} | Sort-Object -Descending | Select-Object -First 1)+1
# Now in this we kill two birds with one stone.
# It will create the "Reports" folder but it also creates "Revision#" folder too.
New-Item -Path "$($Project.Fullname)\Revision$NextRevision\Reports" -Type Directory
# Move on to the next project folder.
# This untested example loop requires PowerShell version 3.0.
}
PowerShell 3.0 installation.
Here's a simple one that worked for me. It checks whether the path exists, and if it doesn't, it will create not only the root path, but all sub-directories also:
$rptpath = "C:\temp\reports\exchange"
if (!(test-path -path $rptpath)) {new-item -path $rptpath -itemtype directory}
I wanted to be able to easily let users create a default profile for PowerShell to override some settings, and ended up with the following one-liner (multiple statements yes, but can be pasted into PowerShell and executed at once, which was the main goal):
cls; [string]$filePath = $profile; [string]$fileContents = '<our standard settings>'; if(!(Test-Path $filePath)){md -Force ([System.IO.Path]::GetDirectoryName($filePath)) | Out-Null; $fileContents | sc $filePath; Write-Host 'File created!'; } else { Write-Warning 'File already exists!' };
For readability, here's how I would do it in a .ps1 file instead:
cls; # Clear console to better notice the results
[string]$filePath = $profile; # Declared as string, to allow the use of texts without plings and still not fail.
[string]$fileContents = '<our standard settings>'; # Statements can now be written on individual lines, instead of semicolon separated.
if(!(Test-Path $filePath)) {
New-Item -Force ([System.IO.Path]::GetDirectoryName($filePath)) | Out-Null; # Ignore output of creating directory
$fileContents | Set-Content $filePath; # Creates a new file with the input
Write-Host 'File created!';
}
else {
Write-Warning "File already exists! To remove the file, run the command: Remove-Item $filePath";
};
$mWarningColor = 'Red'
<#
.SYNOPSIS
Creates a new directory.
.DESCRIPTION
Creates a new directory. If the directory already exists, the directory will
not be overwritten. Instead a warning message that the directory already
exists will be output.
.OUTPUT
If the directory already exists, the directory will not be overwritten.
Instead a warning message that the directory already exists will be output.
.EXAMPLE
Sal-New-Directory -DirectoryPath '.\output'
#>
function Sal-New-Directory {
param(
[parameter(mandatory=$true)]
[String]
$DirectoryPath
)
$ErrorActionPreference = "Stop"
try {
if (!(Test-Path -Path $DirectoryPath -PathType Container)) {
# Sal-New-Directory is not designed to take multiple
# directories. However, we use foreach to supress the native output
# and substitute with a custom message.
New-Item -Path $DirectoryPath -ItemType Container | `
foreach {'Created ' + $_.FullName}
} else {
Write-Host "$DirectoryPath already exists and" `
"so will not be (re)created." `
-ForegroundColor $mWarningColor
}
} finally {
$ErrorActionPreference = "Continue"
}
}
"Sal" is just an arbitrary prefix for my own library. You could remove it or replace it with your own.
Another example (place here because it otherwise ruins stackoverflow syntax highlighting):
Sal-New-Directory -DirectoryPath ($mCARootDir + "private\")
Example, create a 'Reports' folder inside of the script's folder.
$ReportsDir = $PSScriptRoot + '\Reports'
$CreateReportsDir = [System.IO.Directory]::CreateDirectory($ReportsDir)

Auto-Escape dynamic strings in Powershell

I've got a string that will be dynamically generated from a 3rd party application
$somePath = "D:\some\path\name.of - my file [20_32_21].mp4"
I need to be able to verify this path in a function.
$somePath = "D:\some\path\name.of - my file [20_32_21].mp4"
Function ValidatePath{
Param($path)
if(Test-Path $path){
Write-Host "Worked"
} else {
Write-Host "Didn't Work"
}
}
ValidatePath $somePath
# DIDN'T WORK
The problem is that it fails on the square brackets.
How can I automatically escape the square brackets in order to validate the file?
# Path needs to look like this
$somePath = "D:\some\path\name.of - my file ``[20_32_21``].mp4"
ValidatePath $somePath
# WORKED!!!
Use -LiteralPath instead of -Path; e.g.:
if ( test-path -literalpath $path ) {
....
}
Bill
Can you try using "test-path -literalpath $path" ?