Deleting pictures based on dimensions with PowerShell - image

I would like to delete all VERTICAL and SMALL pictures from a certain folder.
I have a folder that I do not want the vertical pictures or pictures with dimensions less than 600 x 600 pixels. I believe that PowerShell is the best thing to use since I cannot get Python to work on my computer.
I am doing this because I do not want to manually delete the vertical/small pictures from my folder each day. (It gets new ones every day)
Any help would be greatly appreciated!!
Here is my code :
cd C:\Users\Jack\Desktop\Test
$c = 5
Function Get-FileMetaData {
Param([string[]]$folder)
foreach($sFolder in $folder) {
$a = 0
$b = 1
$objShell = New-Object -ComObject Shell.Application
$objFolder = $objShell.namespace($sFolder)
foreach ($File in $objFolder.items()) {
$FileMetaData = New-Object PSOBJECT
for ($a ; $a -le 266; $a++) {
if($objFolder.getDetailsOf($File, $a)) {
$hash += #{$($objFolder.getDetailsOf($objFolder.items, $a)) =
$($objFolder.getDetailsOf($File, $a)) }
$FileMetaData | Add-Member $hash
if ($($objFolder.getDetailsOf($objFolder.items, $a)) -eq "Height") {
Write-Host $($objFolder.getDetailsOf($objFolder.items, $a)) =====
$($objFolder.getDetailsOf($File, $a))
}
if ($($objFolder.getDetailsOf($objFolder.items, $a)) -eq "Width") {
Write-Host $($objFolder.getDetailsOf($objFolder.items, $a)) =====
$($objFolder.getDetailsOf($File, $a))
}
if ($($objFolder.getDetailsOf($objFolder.items, $a)) -eq "Name") {
Write-Host $($objFolder.getDetailsOf($objFolder.items, $a)) =====
$($objFolder.getDetailsOf($File, $a))
}
$b++
$hash.clear()
} #end if
} #end for
Write-Host $a
$a=0
$FileMetaData
} #end foreach $file
$c++
Write-Host c = $c
} #end foreach $sfolder
} #end Get-FileMetaData
Write-Host c = $c
$h = Get-FileMetaData C:\Users\Jack\Desktop\Test | select Height
$w = Get-FileMetaData C:\Users\Jack\Desktop\Test | select Width
$n = Get-FileMetaData C:\Users\Jack\Desktop\Test | select Name
$h
Write-Host w = $w
Write-Host name = $n
$SpecChars = '!', "{", "}", '"', '£', '$', '%', '&', '^', '*', '(', ')', '#', '=', '+', '¬', '`', '\', '<', '>', '?', '/', ':', ';', '#', '~', "'", '-', "Name", "N", "a", "m", "e", ' '
$remspecchars = [string]::join('|', ($SpecChars | % {[regex]::escape($_)}))
if (($h) -replace '\D+(\d+)','$1' -gt ($w) -replace '\D+(\d+)','$1') {
Write-Host "VERTICAL"
Write-Host name = $n
$d = $n -replace $remspecchars, ""
$d.split()
Write-Host $d
$tally = 0
while($tally -ne $d.Count) {
del $d[$tally]
$tally++
}
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
Write-Host "Finished"

try this
$folder = 'C:\temp\Pictures\'
$image = New-Object -ComObject Wia.ImageFile
$pictures = Get-ChildItem $folder *.jpg | ForEach-Object {
$image.LoadFile($_.fullname)
$size = $image.Width.ToString() + 'x' + $image.Height.ToString()
$orientation = $image.Properties | ? {$_.name -eq 'Orientation'} | % {$_.value}
if ($orientation -eq 6) {
$rotated = $true
} else {
$rotated = $false
}
$heightGtWidth = if ([int]$image.Height.ToString() -gt [int]$image.Width.ToString()) {
$true
} else {
$false
}
[pscustomobject]#{
Fullname = $_.FullName
Size = $size
Rotated = $rotated
HeightGtWidth = $heightGtWidth
}
}
$pictures

Related

How to collect system monitor information remotly using powershell?

I have code to collect system information remotely and create a csv file ,below,
Param(
[Parameter(Mandatory=$true, position=0)][string]$infile,
[Parameter(Mandatory=$true, position=1)][string]$outfile
)
#Column header in input CSV file that contains the host name
$ColumnHeader = "ComputerName"
$HostList = import-csv $infile | select-object $ColumnHeader
$out = #()
foreach($object in $HostList) {
$os = Get-WmiObject -computername $object.("ComputerName") -class win32_operatingsystem
$vol = Get-WmiObject -computername $object.("ComputerName") -class Win32_Volume
$net = Get-WmiObject -computername $object.("ComputerName") -class Win32_NetworkAdapterConfiguration | where-object { $_.IPAddress -ne $null }
$DeviceInfo= #{}
$DeviceInfo.add("Operating System", $os.name.split("|")[0])
$DeviceInfo.add("Version", $os.Version)
$DeviceInfo.add("Architecture", $os.OSArchitecture)
$DeviceInfo.add("Serial Number", $os.SerialNumber)
$DeviceInfo.add("Organization", $os.Organization)
$DeviceInfo.add("Disk Capacity", "$([math]::floor($vol.Capacity/ (1024 * 1024 * 1024 )) )" + " GB" )
$DeviceInfo.add("Free Capacity", "$([math]::floor($vol.FreeSpace/ (1024 * 1024 * 1024 )))" + " GB" )
$DeviceInfo.add("System Name", $vol.SystemName)
$DeviceInfo.add("File System", $vol.FileSystem)
$DeviceInfo.add("IP Address", ($net.IPAddress -join (", ")))
$DeviceInfo.add("Subnet", ($net.IPSubnet -join (", ")))
$DeviceInfo.add("MAC Address", $net.MACAddress )
$out += New-Object PSObject -Property $DeviceInfo | Select-Object `
"System Name", "Organization", "Serial Number","Operating System", `
"Version","Architecture","File System","Disk Capacity", `
"Free Capacity","MAC Address","IP Address","Subnet"
Write-Verbose ($out | Out-String) -Verbose
$out | Export-CSV $outfile -NoTypeInformation
}
and i have a script to get monitor information
function Decode {
If ($args[0] -is [System.Array]) {
[System.Text.Encoding]::ASCII.GetString($args[0])
}
Else {
"Not Found"
}
}
ForEach ($Monitor in Get-WmiObject WmiMonitorID -Namespace root\wmi) {
$Manufacturer = Decode $Monitor.ManufacturerName -notmatch 0
$Name = Decode $Monitor.UserFriendlyName -notmatch 0
$Serial = Decode $Monitor.SerialNumberID -notmatch 0
$ManufactureWeek = (Get-WmiObject WmiMonitorID -Namespace root\wmi).WeekofManufacture
$ManufactureYear = (Get-WmiObject WmiMonitorID -Namespace root\wmi).YearOfManufacture
echo "Manufacturer: $Manufacturer`nName: $Name`nSerial Number: $Serial"
echo "Week of Manufacture: $ManufactureWeek"
echo "Year of Manufacture: $ManufactureYear"
}
how can i combine these codes to get monitor information remotly,
how can i get monitor information remotely???????????
You may also update your monitor script. With more than one monitor, it will not work correctly.
function Decode {
If ($args[0] -is [System.Array]) {
[System.Text.Encoding]::ASCII.GetString($args[0])
}
Else {
"Not Found"
}
}
ForEach ($Monitor in Get-WmiObject WmiMonitorID -Namespace root\wmi) {
$Manufacturer = Decode $Monitor.ManufacturerName -notmatch 0
$Name = Decode $Monitor.UserFriendlyName -notmatch 0
$Serial = Decode $Monitor.SerialNumberID -notmatch 0
$ManufactureWeek = $Monitor.WeekofManufacture
$ManufactureYear = $Monitor.YearOfManufacture
echo "Manufacturer: $Manufacturer`nName: $Name`nSerial Number: $Serial"
echo "Week of Manufacture: $ManufactureWeek"
echo "Year of Manufacture: $ManufactureYear"
}

PowerShell | Need some performance improvement

I have written a powershell script for archival of old log files or say some output file of web application which is in TBs but the script is taking very long time. I have done some improvement but not able to speed up more from here.
Code:
#region Archive Files using 7zip
[cmdletbinding()]
Param
(
[Parameter(Mandatory=$true, HelpMessage = "Path needs to be with trailing slash at the end of location." )]
[string]$SourceFilesPath
)
$7zip = "C:\Program Files\7-Zip\7z.exe"
$FilePath = ""
foreach ( $filename in $(Get-ChildItem $SourceFilesPath -Force -Recurse | where {$_.LastWriteTime -lt (get-date).AddDays(-1).ToShortDateString()}))
{
$FilePath = Get-ItemProperty $filename.FullName
$ZipFilePath = $filename.Directory.ToString() + "\ZippedFiles" + "\Archive_" + $filename.LastWriteTime.ToString("MMddyyyy") + ".7z"
$tempPath = ("-w"+"C:\Temp")
$OutputData = &$7zip a $tempPath -t7z $ZipFilePath $FilePath
$OutputData
if ($OutputData -contains "Everything is OK")
{
Remove-Item $FilePath -Force
Write-Output "File removed $FilePath"
}
Get-Item $ZipFilePath | ForEach-Object {$_.LastWriteTime = $filename.LastWriteTime}
}
#endregion
#region Archive Files using 7zip
[cmdletbinding()]
Param
(
[Parameter(Mandatory = $true, HelpMessage = 'Path needs to be with trailing slash at the end of location.' )]
[string]$SourceFilesPath
)
Import-Module ..\Invoke-Parallel.ps1 # Download from PSGallery
$7zip = 'C:\Program Files\7-Zip\7z.exe'
$fileToArchive = $(Get-ChildItem $SourceFilesPath -Force -Recurse | Where-Object -FilterScript {
$_.LastWriteTime -lt (Get-Date).AddDays(-1).ToShortDateString()
})
$counter = 0
$groupSize = 2000 # Will group items by 2,000 increments
$groups = $fileToArchive | Group-Object -Property {
[math]::Floor($counter++ / $groupSize)
}
$groups
# This will spawn multiple instances of 7zip - depending on how many groups of 2,000 files exist
$groups.Group | Invoke-Parallel -ScriptBlock {
$FilePath = $null
$fileName = $_
$FilePath = Get-ItemProperty -Path $fileName.FullName
$ZipFilePath = $fileName.Directory.ToString() + '\ZippedFiles' + '\Archive_' + $fileName.LastWriteTime.ToString('MMddyyyy') + '.7z'
$tempPath = ('-w'+'C:\Temp')
$OutputData = &$Using:7zip a $tempPath -t7z $ZipFilePath $FilePath
$OutputData
if ($OutputData -contains 'Everything is OK')
{
Remove-Item $FilePath -Force
Write-Output -InputObject "File removed $FilePath"
}
Get-Item $ZipFilePath | ForEach-Object -Process {
$_.LastWriteTime = $fileName.LastWriteTime
}
}

Can copy & paste be emulated in windows CMD?

In a batch script can "Windows Explorer style" copy & paste be used?
For example
copy example.exe
some arbitrary commands
paste example.exe
Update: copying to the clipboard can do done through cmd but
It looks like it's not possible to paste anything but text with out third party utilities like WinClip & Paste
Using PowerShell it is possible to copy a list of files and folders to [Windows.Forms.Clipboard]::SetFileDropList($collection) and to paste using [Windows.Forms.Clipboard]::GetFileDropList() along with standard file copy or stream reader / writer methods. These methods truly use the clipboard, so files copied through Explorer can be pasted from the console, and vice versa. As a bonus, using scripting to manipulate the clipboard FileDropList allows you to append files to the list from multiple locations -- something the GUI interface doesn't allow.
PowerShell scripts can be created as Batch + PowerShell polyglots. So the answer to your question is, yes, it is possible to do what you want with .bat scripts.
fcopy.bat:
Usage:
fcopy.bat [switch] filemask [filemask [filemask [etc.]]]
fcopy.bat /?
Code:
<# : fcopy.bat -- https://stackoverflow.com/a/43924711/1683264
#echo off & setlocal
if "%~1"=="" ( goto usage ) else if "%~1"=="/?" goto usage
set args=%*
rem // kludge for PowerShell's reluctance to start in a dir containing []
set "wd=%CD%"
powershell -STA -noprofile "iex (${%~f0} | out-string)"
goto :EOF
:usage
echo Usage: %~nx0 [switch] filemask [filemask [filemask [...]]]
echo example: %~nx0 *.jpg *.gif *.bmp
echo;
echo Switches:
echo /L list current contents of clipboard file droplist
echo /C clear clipboard
echo /X cut files (Without this switch, the action is copy.)
echo /A append files to existing clipboard file droplist
goto :EOF
: end batch / begin powershell #>
$col = new-object Collections.Specialized.StringCollection
Add-Type -AssemblyName System.Windows.Forms
$files = $()
$switches = #{}
# work around PowerShell's inability to start in a directory containing brackets
cd -PSPath $env:wd
# cmd calling PowerShell calling cmd. Awesome. Tokenization of arguments and
# expansion of wildcards is profoundly simpler when using a cmd.exe for loop.
$argv = #(
cmd /c "for %I in ($env:args) do #echo(%~I"
cmd /c "for /D %I in ($env:args) do #echo(%~I"
) -replace "([\[\]])", "```$1"
$argv | ?{$_.length -gt 3 -and (test-path $_)} | %{ $files += ,(gi -force $_).FullName }
$argv | ?{$_ -match "^[/-]\w\W*$"} | %{
switch -wildcard ($_) {
"?a" { $switches["append"] = $true; break }
"?c" { $switches["clear"] = $true; break }
"?l" { $switches["list"] = $true; break }
"?x" { $switches["cut"] = $true; break }
default { "Unrecognized option: $_"; exit 1 }
}
}
if ($switches["clear"]) {
[Windows.Forms.Clipboard]::Clear()
"<empty>"
exit
}
if ($switches["list"] -and [Windows.Forms.Clipboard]::ContainsFileDropList()) {
$cut = [windows.forms.clipboard]::GetData("Preferred DropEffect").ReadByte() -eq 2
[Windows.Forms.Clipboard]::GetFileDropList() | %{
if ($cut) { write-host -f DarkGray $_ } else { $_ }
}
}
if ($files.Length) {
$data = new-object Windows.Forms.DataObject
if ($switches["cut"]) { $action = 2 } else { $action = 5 }
$effect = [byte[]]($action, 0, 0, 0)
$drop = new-object IO.MemoryStream
$drop.Write($effect, 0, $effect.Length)
if ($switches["append"] -and [Windows.Forms.Clipboard]::ContainsFileDropList()) {
[Windows.Forms.Clipboard]::GetFileDropList() | %{ $files += ,$_ }
}
$color = ("DarkGray","Gray")[!$switches["cut"]]
$files | select -uniq | %{ write-host -f $color $col[$col.Add($_)] }
$data.SetFileDropList($col)
$data.SetData("Preferred DropEffect", $drop)
[Windows.Forms.Clipboard]::Clear()
[Windows.Forms.Clipboard]::SetDataObject($data, $true)
$drop.Close()
}
paste.bat:
Usage:
paste.bat [destination]
Code:
<# : paste.bat -- https://stackoverflow.com/a/43924711/1683264
#echo off & setlocal
set args=%*
set "wd=%CD%"
powershell -STA -noprofile "iex (${%~f0} | out-string)"
goto :EOF
: end batch / begin powershell #>
$files = #()
[uint64]$totalbytes = 0
# kludge for PowerShell's reluctance to start in a path containing []
cd -PSPath $env:wd
Add-Type -AssemblyName System.Windows.Forms
if (-not [Windows.Forms.Clipboard]::ContainsFileDropList()) { exit }
# cut = 2; copy = 5
$de = [Windows.Forms.Clipboard]::GetData("Preferred DropEffect")
if ($de) {$cut = $de.ReadByte() -eq 2} else {$cut = $false}
function newdir ([string]$dir) {
[void](md $dir)
write-host -nonewline "* " -f cyan
write-host -nonewline "Created "
write-host $dir -f white
}
if ($env:args) {
[string[]]$argv = cmd /c "for %I in ($env:args) do #echo(%~I"
if (test-path -PSPath $argv[0] -type Container) {
try { cd -PSPath $argv[0] }
catch { write-host -f red "* Unable to change directory to $($argv[0])"; exit 1 }
} else {
try { newdir $argv[0] }
catch { write-host -f red "* Unable to create $($argv[0])"; exit 1 }
cd -PSPath $argv[0]
}
}
Add-Type #'
using System;
using System.Runtime.InteropServices;
namespace shlwapi {
public static class dll {
[DllImport("shlwapi.dll")]
public static extern long StrFormatByteSize64(ulong fileSize,
System.Text.StringBuilder buffer, int bufferSize);
}
}
'#
function num2size ($num) {
$sb = new-object Text.StringBuilder 16
[void][shlwapi.dll]::StrFormatByteSize64($num, $sb, $sb.Capacity)
$sb.ToString()
}
# returns the true drive letter, even if the supplied path contains a junction / symlink
function Resolve-Drive ([string]$path) {
while ($path.Length -gt 3) {
$dir = gi -force -PSPath $path
if ($dir.Attributes -band [IO.FileAttributes]::ReparsePoint) {
$path = $dir.Target
if ($path.Length -eq 3) { break }
}
$path = (resolve-path "$path\..").Path
}
$path
}
function Move-File ([string]$from, [string]$to) {
$srcdrive = Resolve-Drive $from
$destdrive = Resolve-Drive (Convert-Path .)
if ($srcdrive -eq $destdrive) {
Move-Item $from $to -force
write-host -n -f green "* "
write-host -n -f white (gi -force -PSPath $to).Name
write-host " moved."
} else {
Copy-File $from $to "Moving"
gi -force -PSPath $from | Remove-Item -force
}
}
# based on https://stackoverflow.com/a/13658936/1683264
function Copy-File {
param([string]$from, [string]$to, [string]$action = "Copying")
if (test-path -type leaf -PSPath $to) { gi -force -PSPath $to | Remove-Item -force }
$ffile = [io.file]::OpenRead($from)
$tofile = [io.file]::OpenWrite($to)
$fileobj = gi -force -PSPath $tofile.Name
$filesize = $ffile.length
$size = num2size $filesize
try {
if ($filesize -ge 16*1024*1024) {
$buffersize = 16*1024*1024
} else { $buffersize = $filesize }
Write-Progress `
-Id 1 `
-Activity "0% $action $size file" `
-status $fileobj.Name `
-PercentComplete 0
$sw = [System.Diagnostics.Stopwatch]::StartNew();
[byte[]]$buff = new-object byte[] $buffersize
[uint64]$total = [uint64]$count = 0
do {
$count = $ffile.Read($buff, 0, $buff.Length)
$tofile.Write($buff, 0, $count)
$total += $count
if (!$ffile.Length) {
$pctcomp = 0
} else {
[int]$pctcomp = ([int]($total/$ffile.Length* 100))
}
[int]$secselapsed = [int]($sw.elapsedmilliseconds.ToString())/1000
if ( $secselapsed -ne 0 ) {
[single]$xferrate = (($total/$secselapsed)/1mb)
} else {
[single]$xferrate = 0.0
}
if ($total % 1mb -eq 0) {
if ($pctcomp -gt 0) {
[int]$secsleft = ((($secselapsed/$pctcomp)* 100)-$secselapsed)
} else {
[int]$secsleft = 0
}
Write-Progress `
-Id 1 `
-Activity ($pctcomp.ToString() + "% $action $size file # " + `
"{0:n2}" -f $xferrate + " MB/s") `
-status $fileobj.Name `
-PercentComplete $pctcomp `
-SecondsRemaining $secsleft
}
} while ($count -gt 0)
$sw.Stop()
$sw.Reset()
}
finally {
$tofile.Close()
$ffile.Close()
$ffile = gi -force -PSPath $from
$fileobj.CreationTime = $ffile.CreationTime
$fileobj.LastWriteTime = $ffile.LastWriteTime
if ( $secselapsed -ne 0 ) {
[string]$xferrate = "{0:n2} MB" -f (($total/$secselapsed)/1mb)
} else {
[string]$xferrate = num2size $fileobj.Length
}
write-host -nonewline "* " -f green
write-host -nonewline $fileobj.Name -f white
write-host (" written in $secselapsed second{0} at $xferrate/s." -f (`
"s" * ($secselapsed -ne 1)));
}
}
[Windows.Forms.Clipboard]::GetFileDropList() | %{
if (test-path -PSPath $_ -Type Leaf) {
$add = #($_.Trim(), ((Convert-Path .) + "\" + (gi -force -PSPath $_).Name))
if ($files -notcontains $add) {
$totalbytes += (gi -force -PSPath $_).Length
$files += ,$add
}
} else {
if (test-path -PSPath $_ -Type Container) {
$src = (Convert-Path -PSPath $_).Trim()
$dest = (Convert-Path .) + "\" + (gi -force -PSPath $src).Name
if (!(test-path -PSPath $dest)) { newdir $dest }
gci -PSPath $src -recurse -force | %{
$dest1 = $dest + $_.FullName.Replace($src, '')
if ((test-path -PSPath $_.FullName -Type Container) -and !(test-path -PSPath $dest1)) {
newdir $dest1
}
if (test-path -PSPath $_.FullName -Type Leaf) {
$add = #($_.FullName.Trim(), $dest1)
if ($files -notcontains $add) {
$totalbytes += $_.Length
$files += ,$add
}
}
}
}
}
}
[string]$totalsize = num2size $totalbytes
$destdrive = resolve-drive (Convert-Path .)
$capacity = (Get-PSDrive ($destdrive -split ':')[0]).Free
if ($totalbytes -gt $capacity) {
write-host -f red "* Not enough space on $destdrive"
exit 1
}
for ($i=0; $i -lt $files.length; $i++) {
Write-Progress `
-Activity "Pasting to $(Convert-Path .)" `
-Status ("Total Progress {0}/{1} files {2} total" `
-f ($i + 1), $files.length, $totalsize) `
-PercentComplete ($i / $files.length * 100)
if ($cut) {
Move-File $files[$i][0] $files[$i][1]
} else {
Copy-File $files[$i][0] $files[$i][1]
}
}
if ($cut) {
[Windows.Forms.Clipboard]::GetFileDropList() | %{
if (test-path -PSPath $_ -type Container) {
gi -force -PSPath $_ | Remove-Item -force -recurse
}
}
[Windows.Forms.Clipboard]::Clear()
}
You can read the clipboard content with powershell,
#echo off
set "myText=This is my text"
rem copy variable content to clipboard
set /p"=%myText%"<nul|clip
rem get clipboard content into variable
set "psCmd=powershell -Command "add-type -an system.windows.forms; [System.Windows.Forms.Clipboard]::GetText()""
for /F "usebackq delims=" %%# in (`%psCmd%`) do set "clipContent=%%#"
echo %clipContent%
exit/B

Powershell locking first and last files and I cannot delete them without close powershell ISE

So I have a Powershell ISE ( tried running as administrator and w/o ) and it is created dummy .mdf file , 50 of them
Problem is that it holds onto the 1st and last , so copying or deleting them is not working ...
This is my script
param(
$amount = 50 # $(throw "Please give an amount of files to be created")
, $size = 5 # $(throw "Please give a the size of the files")
, $folder = "C:\dev\powershell\oldlocation" # $(throw "Please give an output folder wehere the files need to be created")
, $name = 'db' # $null
, $extension = '.mdf' # $null .mdf / .ldf
)
CLS
# Check for input
if(Test-Path $folder)
{
if($name -eq $null)
{
Write-Host "No filename given. Using default setting 'dummy'" -ForegroundColor Yellow
$name = 'dummy'
}
if($extension -eq $null)
{
Write-Host "No filename extension given. Using default setting '.txt'" -ForegroundColor Yellow
$extension = 'txt'
}
elseif($extension -contains '.')
{
$extension = $extension.Substring(($extension.LastIndexOf(".") + 1), ($extension.Length - 1))
}
for($i = 1; $i -le $amount; $i++)
{
$path = $folder + '\' + $name + '_' + $i + '.' + $extension
$file = [io.file]::Create($path)
$file.SetLength($size)
$file.Close
sleep 0.5
}
}
else{
Write-Host "The folder $folder doesn't exist" -ForegroundColor Red
Exit(0)
}
When () are omitted on a method, it returns the Overload Definitions. So the line where you are trying to close the file just needs ().
$file.Close()
If you see OverloadDefinitions ever returned, that's what to look for.

Powershell passing variables to a job

Function start
{
$BackupList = Import-Csv C:\file.csv -Delimiter ";"
ForEach($computer in $BackupList)
{
$arrayBackup = ($computer.Backup).split(".")
$backupdate = Get-Date -Day $arrayBackup[0] -Month $arrayBackup[1] -Year $arrayBackup[2]
$datetoday = Get-Date -format d
$countingday = (get-date $datetoday).AddMonths(-3)
if ($Zahl -eq 1)
{
if ($backupdate -le $countingday)
{
$global:client = $computer.computername
$global:mac = $computer.MAC
$global:Name = $computer.device
$global:lastsaved = [int]$computer.lastsavetime
if ($computer.computername -match $Client)
{
{
$computer.Backup = $datetoday
if ($lastsaved -ne 4)
{
$lastsaved++
}
else
{
$lastsaved = 1
}
if ($lastsaved -eq 1)
{
$global:savingplace = "\\Savingplace1"
}
elseif ($lastsaved -eq 2)
{
$global:savingplace = "\\Savingplace2"
}
elseif ($lastsaved -eq 3)
{
$global:savingplace = "\\Savingplace3"
}
elseif ($lastsaved -eq 4)
{
$global:savingplace = "\\Savingplace4"
}
$computer.lastsavetime = $lastsaved
}
}
Start-Job -InitializationScript $functions -ScriptBlock {NASLOGIN} -argumentlist $_ | Receive-Job
}
}
}
}
I am reading some information out of a csv-file.
i want to pass some of this information read to a job.
in the job im doing quiet a lot of function calls and operations using this variables.
but at the moment there is no variable passed to the job.
how can i fix this?
You are passing $_ to the ArgumentList parameter but I don't see anywhere in where you code where there is a pipeline active - hence $_ is not defined. To pass variables to the job, specify valid variables in the ArgumentList e.g.:
$foo = 'foo'
$bar = 'bar'
Start-Job {param($a, $b) "a is $a, b is $b"} -Arg $foo,$bar | Receive-Job -Wait
Start-Job -ScriptBlock {NASLOGIN $args[0]$args[1]$args[2]$args[3]$args[4]} -argumentlist $var1,$var2,$var3,$var4,$var5 -InitializationScript $functions
}
}
}
$functions =
{
Function NASLogin
{
$var1 = $args[0]
$var2 = $args[1]
$var3 = $args[2]
$var4 = $args[3]
$var5 = $args[4]
Have done it like this and it works.
Thanks for your help.

Resources