Path is denied, not able to run ps1 script - powershell

Trying to run the following, but getting a message path is denied
I am new to powershell
Set-Location -Path "C:\work\test
$newFILEStest=(1..100)
foreach($f in $newFILEStest)
{
$newFiletest1="business" +$f + ".txt"
new-item $newfiletest1 -path $source_businesspath
}
$source_businesspath = "C:\work\test\$(Get-Date -Format "yyyy-MM-dd")\business
Goal is: loop generate files such as business.txt inside of the subfolder: business.
Be able to run the ps1 file outside of PS command line

I've fixed the many quoting and logic problems here.
$source_businesspath = "work\test\$(Get-Date -Format 'yyyy-MM-dd')\business"
mkdir $source_businesspath
$newFILEStest=(1..10)
foreach($f in $newFILEStest)
{
$newFiletest1="business" +$f + ".txt"
new-item -name $newfiletest1 -path $source_businesspath
}

You need to make sure that your destination path exists before you create items in it. A simple Test-Path will be able to validate that the directory exists.
Obviously, you also need to have permission to create the directory and files.
$source_businesspath = "C:\Work\Test\$(Get-Date -Format 'yyyy-MM-dd')\business"
if (-not (Test-Path -Path $source_businesspath)) {
New-Item -Path $source_businesspath -ItemType Directory -Force
}
$newFILEStest = (1..10)
foreach ($f in $newFILEStest) {
$newFiletest1 = "business" + $f + ".txt"
New-Item -Path $source_businesspath -Name $newfiletest1
}

Related

powershell create directory from path

the paths are like this and none of these directory exist:
"D:\temp\test\abc.txt"
"D:\temp2\test2\abc2.txt"
"D:\temp1\abc.txt"
I am trying to split the path and create directories only.
I am trying below:
New-Item -Path "D:\temp\testing\abc.txt" -ItemType file
Split-Path -Path "D:\temp\testing\abc.txt" -Resolve –IsAbsolute
[edit - didn't see the comment by Tuttu. [*blush*] i will leave this here, but that one is the 1st answer.]
i think what you are looking for is the Split-Path cmdlet. [grin] something like this ...
$PathList = #(
'c:\temp\test1\abc.txt'
'c:\temp\test2\subtest2-1\abc2.txt'
'c:\temp\test3\subtest3-1\subtest3-1-1\abc.txt'
)
foreach ($PL_Item in $PathList)
{
$NewDir = Split-Path -Path $PL_Item -Parent
if (-not (Test-Path -LiteralPath $NewDir))
{
$Null = New-Item -Path $NewDir -ItemType Directory -Force
}
}
that made 3 new directories, two of them with sub-directories.
note that this does NOT take into account any input path that has no terminating file ... you will always get the parent path.

Powershell: You cannot call a null-valued expression

Hello Stack Overflow Community,
at the moment I'm struggling with this code (it's not that beautiful):
$filepath = "C:\inetpub\logs\LogFiles"
$filearchivepath = "C:\inetpub\logs"
$daystoarchive = 1
$_ = "";
function create-7zip([String] $aDirectory, [String] $aZipfile){
#change the path where you downloaded the 7z exe
[string]$pathToZipExe = "C:\Users\kschweiger\Downloads\7za.exe";
[Array]$arguments = "a", "-tzip", "$aZipfile", "$aDirectory";
& $pathToZipExe $arguments;
}
#Create a new folder with the specific date
$ArchiveFolder = (Get-Date -Format dd.MM.yyyy) + " - Logs-Archive"
if(Test-Path "$filearchivepath\$ArchiveFolder"){
Write-Host "Folder already exists!"
}else{
New-Item -Path $filearchivepath -Name $ArchiveFolder -ItemType directory
}
#Save alle files older than X days into $Files
$Files = Get-ChildItem -Path $filepath -Recurse | where {$_.LastWriteTime -lt (Get-Date).AddDays(-$daystoarchive)}
#Copy/Move files and keep folder structure
foreach ($File in $Files){
$NewPath = $File.DirectoryName.Replace($filepath,"")
if (!(Test-Path "$filearchivepath\$ArchiveFolder\$NewPath"))
{
New-Item -Path "$filearchivepath\$ArchiveFolder\$NewPath" -ItemType Directory
}
$File | Copy-Item -Destination "$filearchivepath\$ArchiveFolder\$NewPath"
}
#Compress folder
if(Test-Path "$filearchivepath\$ArchiveFolder.zip"){
Write-Host "Archive-File already exists!"
}else{
#[IO.Compression.ZipFile]::CreateFromDirectory("$filearchivepath\$ArchiveFolder","$filearchivepath\$ArchiveFolder.zip")
create-7zip "$filearchivepath\$ArchiveFolder" "$filearchivepath\$ArchiveFolder.zip"
#Delete Folder
Remove-Item -Path "$filearchivepath\$ArchiveFolder" -Recurse -Force
}
The code works. but I also get a error message called:
You cannot call a null-valued expression
How can I resolve this?
Get-ChildItem by default returns files and folders. If you need only files, you should use -File. Otherwise, your $Files will contain folders too (as they have LastWriteTime property).
If you try to run .DirectoryName.Replace($filepath,"") on a folder, it'll return such error as you cannot run replacing on $null.
Update: for PowerShell 2.0 you can use | where { ! $_.PSIsContainer } (source)
How can I troubleshoot it by myself?
In your error you can see which line is broken:
$NewPath = $File.DirectoryName.Replace($filepath,"")
All you have to do to troubleshoot such situations is to list all the involved variables and check their values. You could do it like this:
$File
$File.DirectoryName
Pause
$NewPath = $File.DirectoryName.Replace($filepath,"")
Using Pause can be useful as it'll wait for you to press Enter before continuing.

Copy Files on Same Directory using Powershell

I am trying to write powershell Script which will create backupfolder on same Path where Application exist and need to copy the folders & files into backupfolder before deploying. Below are the command was using to perform but am getting error
$Source = "C:\XYZ"
$BackupFolder = New-Item -ItemType Directory -Force -Path $source_$(Get-Date)
Copy-Item -Path $Source\* $BackupFolder -Force
Error: Cannot copy item C:\XYZ\Backup_18-02-2017 on to itself
Try:
Copy-Item $Source\* $BackupFolder -Exclude $BackupFolder
That will eliminate the folder that you are copying into as a source that is being copied from.
Variables can contain underscores. The following works and displays the string "asdf"
$a_ = "adsf"; $a_
Your New-Item cmdlet call should have failed since $source_ is not a variable and would return null. This is default behavior for PowerShell. When I run your code as is I get the following:
New-Item : Cannot find drive. A drive with the name '02/18/2017 22' does not exist.At line:1 char:1
+ New-Item -ItemType Directory -Force -Path "$source_$(Get-Date)" -what ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (02/18/2017 22:String) [New-Item], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.NewItemCommand
So I would have expected your folder variable to be null. wOxxOm brings this up in comment as well
Several options to address what I am sure is the partial source of your issue.
$BackupFolder = New-Item -ItemType Directory -Force -Path "$source`_$(Get-Date)"
$BackupFolder = New-Item -ItemType Directory -Force -Path "$($source)_$(Get-Date)"
$BackupFolder = New-Item -ItemType Directory -Force -Path ("{0}_{1} -f "$source, Get-Date)
You will still have to try and exclude this folder from the copy as well like Keith Hill's answer is telling you
Copy-Item $Source\* $BackupFolder -Exclude $BackupFolder
try Something like this
$Source = "C:\XYZ"
$Destination="{0}{1:yyyyMMdd}" -f $source, (Get-Date)
New-Item -ItemType Directory -Force -Path $Destination
Copy-Item -Path $Source\* $Destination -Recurse -Force
If I understand the question correctly. You want to take "C:\XYZ" and backup into the same directory called "C:\XYZ\backup_$DATE". What you will actually do is create a loop that will break once it reaches the max 248 characters. If we use the -exclude option then we can exclude the backup directory "C:\XYZ\backup_$DATE".
This function will do the trick and also gives you error handling.
Function Get-CopyDirectory{
#####################
# Dynamic Variables #
#####################
$Date = Get-Date -format ddMM-yyyy
$Exclude="Backup*"
####################
# Static Variables #
####################
$AppPath = "F:\Test\"
$BackupPath = "$AppPath\BACKUP_$Date\"
if (Test-Path $BackupPath) {
Write-Host "Backup Exist" -f Cyan
}
else
{
Copy-Item "$AppPath\*" $BackupPath -Exclude $Exclude -recurse -verbose
}
}
CLS
Get-CopyDirectory

powershell Copying files into new directories - best way

I'm using this answer to try to copy files to a new location using a .csv list where OldName is the current file name and NewName is the new name including filepath.
What is the best way to force the script to generate a new folder according to the new path?
For example:
OldName NewName
A.pdf C:\NewFolder\Anew.pdf
This is my script
$Copies = Import-Csv '.\copies.csv' -Header "OldName","NewName"
foreach($File in $Copies) {
New-Item -Force $File.NewName -Type File
Copy-Item $File.OldName $File.NewName
}
But this overwrites any files that stay in the same folder before they get copied.
Replace the line where you create the directory:
New-Item -Force $File.NewName -Type File
With this:
$NewDir = ($File.NewName -as [System.IO.FileInfo]).DirectoryName
If (-not (Test-Path -Path $NewDir)) {
New-Item -ItemType Directory -Path $NewDir -Force | Out-Null
}

Powershell - Copying to a new folder

I am cleaning up some log files and trying to copy it to the new folder that gets created here.
but it fails in the line:
$newpath = join-path $f.directoryname\Cleaned $($f.basename + "_new" + $f.extension)
if I remove the "\Cleaned" part in that line, it works fine. but it copies the cleaned file on the same folder, which is not good.
I am not sure if the way I pass that new folder with the directory name is wrong. How do I do it right?
Function IIS-CleanUp1($path,$file)
{
$f = get-item $path\$file1
$newpath = join-path $f.directoryname\Cleaned $($f.basename + "_new" + $f.extension)
Get-Content $f | ? { $_ -match $control -and $_ -notmatch '^\#'} | Out-File $newpath
}
Function Files($path)
{
$allfiles = Get-ChildItem($path) -name
New-Item -ItemType directory -Path $path\Cleaned
foreach ($file1 in $allfiles)
{
IIS-CleanUp1($path,$file)
}
}
$path1 = "C:\Temp\IIS_CCHECK_AUG\IIS_CCHECK_AUG_202"
Files $path1
Q2:
I like to delete the directory "Cleaned", if it is already there, just above this line.
New-Item -ItemType directory -Path $path\Cleaned
when I try the following it does not work.
Remove-Item $path\Cleaned -force
Any ideas.
Thanks again.
-T
I think you need to have two parameters to join-path. Like join-path C:\ users (note the space). So put every extra path as a separate argument.
You need to fix the first path by adding quotes and get the inside evaluated to add \Cleaned:
$newpath = join-path "$($f.directoryname)\Cleaned" $($f.basename + "_new" + $f.extension)