Chef doesn't call the second line of the PS script - powershell

I'm using Chef Kitchen to do a POC. We have a PowerShell script which goes to a network path, sorts the build based on date [Install shield installer], copies to the VM in a folder.
This script works correctly when I run inside the VM manually using Power Shell. When I run using Chef Kitchen I don't get any error, the recipe is run but only the first line.I can see the folder called Build created in the VM.
I did an experiment and added a second line to create another folder, it worked correctly. So the issue is the logic I used to copy and paste the build doesn't seem to work with Chef.
The first line creates a new folder, the second and third sets the source and destination path. The fourth line copies the build from the network path [Sort by date to get the latest] to the VM. And the last one is to rename.
And also is there an efficient way to copy a file from a network path [Sorting by date] to a VM using Chef?
powershell_script 'CopyBuild' do
code <<-EOH
New-Item -ItemType directory -Path C:\Build
$source = gci \\BuildPath\Build | ? { $_.PSIsContainer } | sort CreationTime -Desc | select -f 1
$destination = "C:\Build"
Copy-Item "\\BuildPath\Build\$source\*" $destination
Get-ChildItem $destination -r -i "*app1*.exe" | Rename-Item -NewName {"Test.exe"}
EOH
end
I also tried this, calling the PS script:
cookbook_file 'getbuild.ps1' do
mode '0755'
end

This looks like a windows remoting problem, your powershell needs the right configuration to be allowed to access network shares.
To verify if this is the case: replace the UNC path and just copy a local directory - if this works you can dig further to setup the requirements for windows remoting, see the following links for further help:
Safely running windows automation operations that fail inside winrm or powershell remoting (see chapter No access to network resources)
Knife issue 655
enabling and using credssp
To sum these links up: you can schedule a local task in your PS which does the copy to achieve this, or setup credssp.

Related

Why do I get an error when trying to deploy a folder of script files with PSDeploy?

I am currently using PSDeploy to deploy my PowerShell script modules to a local PowerShell gallery and it is working great for that. It also works for deploying single files such as my profile.ps1.
Now I am wondering if I can use PSDeploy to deploy other non-PowerShell script files such as my AutoHotkey scripts. For the AHK scripts, the deploy task would only be copying a folder, including script files, from my dev location to a location where I run the scripts.
Unfortunately I keep getting an error while attempting to deploy a folder of script files with PSDeploy.
I created a simple test project on Github to help toubleshoot the error. Anyone can clone this project locally and run a test like I am if they want to.
My test PSDeploy script looks like this:
Deploy FolderTest {
By FileSystem {
FromSource '.\deployFolderFrom'
To '.\deployFolderTo'
}
}
This is how I am running my tests.
# I am running my test in 'G:\_temp'
cd G:\_temp
# Clone the test project to your test folder or in my case 'G:\_temp'
git clone https://github.com/jesmith01/PSDeployTest.git
# Change directory to the PSDeployTest folder.
cd .\PSDeployTest\
# Run this command from PSDeployTest folder.
Invoke-PSDeploy -Verbose
This is my results with verbose setting turned on, error at the end:
My PowerShell version is 7.2.1 as of running this test:
My OS version is Windows 11:
I even tested out this example code from RamblingCookieMonster exactly, without changing anything, and I still get an error:
# Source folders and files
mkdir C:\PSDeployFrom
mkdir C:\PSDeployFrom\MyModule
mkdir C:\PSDeployFrom\SomeScripts
mkdir C:\PSDeployFrom\Deployments
New-Item -ItemType File -Path C:\PSDeployFrom\MyModule\MyModule.psm1
New-Item -ItemType File -Path C:\PSDeployFrom\MyModule\MyModule.psd1
New-Item -ItemType File -Path C:\PSDeployFrom\SomeScripts\Script1.ps1
New-Item -ItemType File -Path C:\PSDeployFrom\SomeScripts\Script2.ps1
# Target folder, with a file that mirror should overwrite
mkdir C:\PSDeployTo
mkdir C:\PSDeployTo\MyModule
New-Item -ItemType File -Path C:\PSDeployTo\MyModule\Remnant.ps1
# Sample PSDeploy.ps1 file
Set-Content C:\PSDeployFrom\Deployments\my.psdeploy.ps1 -Value #'
Deploy ExampleDeployment {
By FileSystem Scripts {
FromSource 'SomeScripts'
To 'C:\PSDeployTo'
Tagged Dev
DependingOn ExampleDeployment-Modules
}
By FileSystem Modules {
FromSource MyModule
To C:\PSDeployTo
Tagged Prod, Module
WithOptions #{
Mirror = $true
}
}
}
'#
Set-Location -Path 'C:\PSDeployFrom'
After running the above sample code:
# Run this command from 'C:\PSDeployFrom' folder.
Invoke-PSDeploy -Verbose
This is my results with verbose setting turned on, getting the same error at the end:
I reviewed a bunch of *.psdeploy.ps1 scripts from others on GitHub, read the documentation, tested out examples from RamblingCookieMonster, tried using absolute paths, relative paths and I even took a peek at the PSDeploy source code where I am getting the error. I still cannot figure out where this error is coming from. It appears what I am doing is right.
Q: Is PSDeploy only intended for deploying PowerShell script modules or can it also be used to deploy non-PowerShell folders and files?
Q: Is it possible my PSDeploy installation is faulty or maybe it is not compatible with PowerShell 7.2.1?
Any help is appreciated. Thanks.
UPDATE: Thanks to #MathiasR.Jessen comment, he gave me the idea to try the same tests with Windows PowerShell 5.1 and they all worked! For now I can just use Windows PowerShell for deployment until I figure out what is broken with PowerShell 7.2.1.
Works with Windows PowerShell 5.1

Copy file from a Network Drive to a local Drive with a Jenkins Agent

So here is the situation, I am trying to automate the copy of some files that are in a network drive into a local folder on one of my servers. The task seems to be simple and when I try the code with PowerShell or with x copy in the command line both are working pretty great.
I've installed a Jenkins agent on this Windows server 2016 server and run the agent as a service. When I try to run the same code from the Jenkins agent, it is never working.
I tried starting the agent service as local system and as the windows network administrator who has all the right
I tried with PowerShell those lines :
Copy-Item -Path "\\server IP\directory\*" -Destination "D:\Directory\" -Verbose
and
Copy-Item -Path "z:\*" -Destination "D:\Directory\" -Verbose
Both return no error but did not copy the files, and when I tried the same code with x copy I just receive no file found and the file was not copied
xcopy "\\server IP\directory\*" "D:\Directory\" /f /s /h /y
xcopy "z:\*" "D:\Directory\" /f /s /h /y
With PowerShell, I also tried inserting the copy-file command into a script and only calling the script with the Jenkins agent, and it also didn't work
I am now running in a circle and wonder how are we supposed to work with the network drive with the Jenkins agent? Or what I am doing wrong ?
Note that other PowerShell code are working great locally.
I tried starting the agent service as local system and as the windows network administrator who has all the right
Local system doesn't have any network permissions by default. This is the machine account, so you would have to give the machine access to "\\server\share". It is not advisable though, because permissions should be granted on finer granularity. Also, local system has too many local rights, which Jenkins doesn't need.
I don't know what you mean by "Windows Network Administrator". It sounds like this one would also have too many rights.
Usually, one creates a dedicated Jenkins (domain) user. This user will be granted access to any network paths it needs. Then you have two options:
Always run Jenkins service as this user (easiest way).
Run Jenkins under another local user and connect to network drives as the domain user only on demand: net use \\server\share /user:YourDomain\Jenkins <Password>. This adds some security as you don't need to give any local permissions to the domain user.
Both return no error but did not copy the files
To improve error reporting, I suggest you set $ErrorActionPreference = 'Stop' at the beginning of your PowerShell scripts. This way the script will stop execution and show an error as soon as the first error happens. I usually wrap my PS scripts in a try/catch block to also show a script stack trace, which makes it much easier to pinpoint error locations:
$ErrorActionPreference = 'Stop' # Make the script stop at the 1st error
try {
Copy-Item -Path "\\server IP\directory\*" -Destination "D:\Directory\" -Verbose
# Possibly more commands...
# Indicate success to Jenkins
exit 0
}
catch {
Write-Host "SCRIPT ERROR: $($_.Exception)"
if( $_.ScriptStackTrace ) {
Write-Host ( "`t$($_.ScriptStackTrace)" -replace '\r?\n', "`n`t" )
}
# Indicate failure to Jenkins
exit 1
}
In this case the stack trace is not much helpful, but it will come in handy, when you call functions of other scripts, which in turn may call other scripts too.

Powershell Dot Slash .\ Starts at the root of a drive

Note: I'm using the built-in PowerShell ISE as my environment
I got a funny issue with dot slash on Powershell. All of my scripts run from a certain folder and there are subfolders that contain data that is needed for them to run.
For example, my scripts are saved at c:\users\chris\posh
Most of the time, I will call input and send output to subfolders like this...
c:\users\chris\posh\inputs
c:\users\chris\posh\output
Therefore I'll have scripts examples that look like this for inputs and outputs:
$hbslist = Get-Content .\inputs\HBS-IP.txt
write-output "$($lat),$($long)" | Out-File .\Outputs\"LatLong.csv" -Append
Lately, when I run the scripts, it cannot locate my files or exe's that I call on. That's because it's trying to look at P:/ instead of c:\users\chris\posh when using .\
Powershell also starts in my P:\ (mapped share drive) for some reason and I cannot figure out as to why my PC is running this way.
It might be a policy on your machine which changes your home directory. You can check the home directory with:
echo $env:HOME
This happens often on corporate machines. If you want to set it back for your powershell environment, you can set it in your profile.ps1.
This is typically stored at:
c:\Users\<Name>\Documents\WindowsPowershell\profile.ps1

PowerShell Script to empty recycle bin works locally but not remotely

I have the following PowerShell script to empty the recycle bin.
$recycleBin = (New-Object -ComObject Shell.Application).NameSpace(0xa)
$recycleBin.Items() | ForEach-Object -Process { Remove-Item -Path $_.Path -Force -Recurse }
The script works locally on my machine. I want to invoke the same script remotely, but it does not work. This script is meant to empty the recycle bin of the (primary) user that is signed in, and the machine has only C drive. I have been invoking remotely many other scripts like removing temporary files of browsers, getting system info, etc. They all work fine.
I am using System.Management.Automation library to invoke the script and I add the remote machine details and admin credentials needed to the Runspace. Here you can find details about the library.
Any ideas why this happens?

Powershell Copy-item command not working in script although it does work when run from a command line

I am on a Windows 7 machine trying to execute a PowerShell script to copy a template directory to another directory. The command I am executing looks like:
Copy-Item -path "$projectsFolder$SourceFolder" -destination "$Test" -recurse -verbose;
The parameters are as follows:
path: C:\Users\username\Documents\Visual Studio 2010\Projects\TemplateSolution\Source
Destination: C:\Users\username\Documents\Visual Studio 2010\Projects\test\source\main
When I run this command at a PowerShell prompt, the files are copied correctly. If I try and execute the command in the script with verbose enabled, it appears to copy the files and directories, but only the top level directory is created in the file system. I am not sure why this would happen and I would appreciate any guidance or troubleshooting steps to perform.
Make sure you put quotes around the directory names if they have spaces in them. Also, you may need the -Force parameter to create destination directories if they do not exist.