I have a powershell script to delete a folder on a bunch of Windows hosts in our cluster.
It runs fine in the ISE and when running local from my laptop. however, I installed powershell on my Centos7.2 machine and when I try to run I get the following error
Join-Path : Cannot process argument because the value of argument "drive" is
null. Change the value of argument "drive" to a non-null value.
At /home/user/powershell/delete_.file.ps1:11 char:20
+ $newfilepath = Join-Path "\\$computer" "$file"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Join-Path],
PSArgumentNullException
+ FullyQualifiedErrorId :
ArgumentNull,Microsoft.PowerShell.Commands.JoinPathCommand
Test-Path : Cannot bind argument to parameter 'Path' because it is null.
At /home/user/powershell/delete_.file.ps1:12 char:19
+ if (test-path $newfilepath) {
+ ~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Test-Path],
ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.TestPathCommand
here is the code to the script
$filelist = #("C$\.file")
$computers = Get-Content /home/user/powershell/sw_win.txt
foreach ($file in $filelist)
{
foreach ($computer in $computers)
{
Write-Host -ForegroundColor Yellow "Analysing $computers"
$newfilepath = Join-Path "\\$computer" "$file"
if (test-path $newfilepath) {
Write-Host "$newfilepath Folder exists"
try
{
Remove-Item $newfilepath -Force -recurse -ErrorAction Stop
}
catch
{
Write-host "Error while deleting $newfilepath on $computer.
`n$($Error[0].Exception.Message)"
}
Write-Host "$newfilepath folder deleted"
} else {
Write-Information -MessageData "Path $newfilepath does not exist"
}
}
}
I think its because $computer is not set, but what doesn't make sense is it works fine using ISE.
Any help would be appreciated
Related
The script included below is now suddenly failing because of the following error. I have not made any changes to it and it's been working for months.
Rename-Item : Cannot bind argument to parameter 'Path' because it is null.
At C:\ImportScripts\FedEx Script\FedExScript.ps1:14 char:14
+ Rename-Item $file $newfilename
+ ~~~~~
+ CategoryInfo : InvalidData: (:) [Rename-Item], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.RenameItemCommand
Add-Type -AssemblyName PresentationCore,PresentationFramework
$curdir=Get-Location
$unc=" " #redacted, but confirmed that working location is correct when running
Set-Location $unc
$dayofweek=([int](Get-date).DayOfWeek)
$fileday=-($dayofweek+3) #change if needed 4:Wednesday, 3:Thursday, etc
$ndate=get-date ((get-date).adddays($fileday)) -Format "yyyyMMdd"
$nyear=get-date ((get-date).adddays($fileday)) -Format "yyyy"
$filename="FedEx_ShipmentDetail_"+$ndate+"*.csv"
$newfilename="FedEx_ShipmentDetail_"+$ndate+".csv"
$fileexists=Test-Path "FedEx_ShipmentDetail_*.csv" -PathType Leaf
if ($fileexists) {
$file = gci ($filename)
Rename-Item $file $newfilename
Set-Location $curdir
$err=cscript "C:\ImportScripts\FedEx Script\FedExScript.vbs"
if ($err -eq 0) {
cscript "C:\ImportScripts\upscleanuptemp.vbs"
Set-Location $unc
mv $newfilename .\$nyear
Set-Location $curdir
[System.Windows.MessageBox]::Show("Import and cleanup completed with no errors.")
}
else {
[System.Windows.MessageBox]::Show("Error in FedExScript.vbs "+$err)
Set-Location $unc
Rename-Item $newfilename $file
Set-Location $curdir
}
}
else {
[System.Windows.MessageBox]::Show("File not found.")
Set-Location $curdir
}
Solved.
Needed to adjust $fileday modifying integer because filename was not matching, as noted in my comments.
ps1 with following content
Write-Output "Download Prerequisite Softwares"
$FolderName = "C:\Softwares\"
$VSCPlusPlusUri = 'https://download.visualstudio.microsoft.com/download/pr/d22ecb93-6eab-4ce1-89f3-97a816c55f04/37ED59A66699C0E5A7EBEEF7352D7C1C2ED5EDE7212950A1B0A8EE289AF4A95B/VC_redist.x64.exe'
if (Test-Path -Path $FolderName) {
Remove-Item $FolderName -Recurse -ErrorAction Ignore
} else {
New-Item $FolderName -ItemType Directory
Write-Output "1) Download and install Visual C++ Runtime"
Start-BitsTransfer –Source $VSCPlusPlusUri -Destination $FolderName
Start-Process 'C:\Softwares\VC_redist.x64.exe' -ArgumentList “/passive” -Wait -Passthru
}
When I execute command line by line (copy single line and paste into Windows PowerShell), it works well but I try to execute .\test.ps1 it throw error below
At C:\1.PowerShell\1.TPX-1418-WindowsServer2016\2.1-DownloadAndInstallVisualCplusPlus.ps1:13 char:23
+ ... Start-BitsTransfer –Source $VSCPlusPlusUri -Destination $FolderName
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The string is missing the terminator: ".
At C:\1.PowerShell\1.TPX-1418-WindowsServer2016\2.1-DownloadAndInstallVisualCplusPlus.ps1:8 char:8
+ } else {
+ ~
Missing closing '}' in statement block or type definition.
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : TerminatorExpectedAtEndOfString
Please help me this case ! Thanks all
Checking if a file exists on a remote machine:
#Check if Dir exists on the machine we are copying from
$dir = ($APPROD001Root + $instance + "\" + $type + "\" + $year + "\" + $monthFormatted)
Write-Host $dir
if(Test-Path -Path $dir){
Write-Host ($dir + " exists!")
$files = Get-ChildItem -Path $dir
#Check if the Dir has files in it
if($files.Length -gt 0){
#Check if the folder exists on the machine we are copying towards, if not create it!
$dirReceivingMachine = ($DBStag01Root + $instance + "\" + $type + "\" + $year + "\" + $monthFormatted)
Write-Host $dirReceivingMachine
if($dirReceivingMachine -eq $null){
Write-Host "the path is null..."
}
$folderExists = Invoke-Command -ScriptBlock { Test-Path -Path $dirReceivingMachine } -Session $session
if(!$folderExists){
Write-Host ("folder " + $dirReceivingMachine + " does not yet exist we want to create it!")
#Invoke-Command - ScriptBlock { New-Item -Path $dirReceivingMachine -ItemType Directory } -Session $session
}
The invoke-command that sets the $folderExists always throws
Cannot bind argument to parameter 'Path' because it is null.
+ CategoryInfo : InvalidData: (:) [Test-Path], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.TestPathCommand
the output I get in terminal is
D:MyData\2018\09
D:\MyData\2018\09 exists!
D:\MyData\2018\09 Cannot bind argument to
parameter 'Path' because it is null.
+ CategoryInfo : InvalidData: (:) [Test-Path], ParameterBindingValidationException
As you can see the Write-Host "The path is null.." never fires, so the variable I am passing into Test-Path is not null yet PS says it is when invoking the command...
No idea why it does this
I came across PowerShell script to log Microsoft Office version of remote computer on domain. I want to run it as logon script to I modified OpenRemoteBaseKey to OpenBaseKey and this is the code:
$version = 0
$reg = [Microsoft.Win32.RegistryKey]::OpenBaseKey('LocalMachine', 'Default')
$reg.OpenSubKey('software\Microsoft\Office').GetSubKeyNames() |% {
if ($_ -match '(\d+)\.') {
if ([int]$matches[1] -gt $version) {
$version = $matches[1]
}
}
}
if ($version) {
Add-Content -Path \\server\share\oversion.txt -Value "$env:computername $env:username : $version"
}
else {
Add-Content -Path \\server\share\oversion.txt -Value "$env:computername $env:username : 0"
}
but now I receive error:
You cannot call a method on a null-valued expression.
At line:4 char:1
+ $reg.OpenSubKey('software\Microsoft\Office').GetSubKeyNames() |% {
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
but not sure what this means since GetSubKeyNames seems valid: https://learn.microsoft.com/en-us/dotnet/api/microsoft.win32.registrykey.getsubkeynames?view=netframework-4.7.2, also it works with OpenRemoteBaseKey, can someone point me to right direction, please?
I'm not sure why OpenRemoteBaseKey works, but OpenBaseKey doesn't because I cannot reproduce that..
You might however try the more Powershell way of doing this:
$version = 0
Get-ChildItem -Path 'HKLM:\SOFTWARE\Microsoft\Office' -Name | Where-Object {$_ -match '(\d+)\.\d+'} | ForEach-Object {
$version = [math]::Max([int]$_, $version)
}
Add-Content -Path \\server\share\oversion.txt -Value "$env:COMPUTERNAME $env:USERNAME : $version"
I am attempting to run a powershell script from my PC against a txt file that contains numerous remote PC's. I want to run a script against that list of PC's that will search a certain file path for specific file name and/or file extension.
I have been attempting to do a for each loop with my txt file inserted as a variable. I am also attempting to get the file names returned to me via the cmdlet "Get-ChildItem."
I have not been able to get anything to work correctly so far. Can anyone point me in the right direction with this? Below are a couple of things I have tried so far...
**
PS C:\Windows\system32> $name= gc env:computername
$computers= get-content -path c:\users\person\Desktop\book2.txt
$csvfile = "c:\temp\$name.csv"
foreach ($computer in $computers) {Get-ChildItem -recurse -filter "C:\Users\*.locky"}
export-csv -filepath $csvfile
**
*
Get-ChildItem : Second path fragment must not be a drive or UNC name.
Parameter name: path2
At line:4 char:36
+ foreach ($computer in $computers) {Get-ChildItem -recurse -filter "C:\Users\*.lo ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (C:\Windows\system32:String) [Get-ChildItem], Argume
ntException
+ FullyQualifiedErrorId : DirArgumentError,Microsoft.PowerShell.Commands.GetChildItemCommand
Export-Csv : A parameter cannot be found that matches parameter name 'filepath'.
At line:5 char:12
+ export-csv -filepath $csvfile
+ ~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Export-Csv], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.ExportCsvCommand
*
AND
C:\Windows\system32> ForEach ($system in (Get-Content C:\temp\Book2.txt))
if ($exists in (Test-Path \\$system\c$\Users\*.locky))
{
Get-Command $exists | fl Path,FileVersion | Out-File c:\temp\results.csv -Append
}
At line:1 char:53
+ ForEach ($system in (Get-Content C:\temp\Book2.txt))
+ ~
Missing statement body in foreach loop.
At line:3 char:14
+ if ($exists in (Test-Path \\$system\c$\Users\*.locky))
+ ~~
Unexpected token 'in' in expression or statement.
At line:3 char:14
+ if ($exists in (Test-Path \\$system\c$\Users\*.locky))
+ ~~
Missing closing ')' after expression in 'if' statement.
At line:3 char:55
+ if ($exists in (Test-Path \\$system\c$\Users\*.locky))
+ ~
Unexpected token ')' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingForeachStatement
Wrong -filter parameter in Get-ChildItem cmdlet. Next code snippet should work:
foreach ($computer in $computers) {"\\$computer\C$\Users"|`
Get-ChildItem -recurse -filter "*.locky"}