Powershell script works locally but not under solarwinds SAM component - powershell

Below is the script which works locally under powershell ISE. But same under SAM Component ie Windows powershell monitor not working
Script checks for doc file under path1 and if exist. It takes copy of the file from path1 and move to Path2 by renaming with timestamp.
$directory = 'path1'
$filter = '*.doc'
$msg = ' '
$com = ","
$count = 0
$stamp = Get-Date -F yyyy-MM-dd_HH-mm
Get-ChildItem -Path $directory -Filter $filter | Foreach-Object {
$msg = $msg + $com + $_.FullName
$dest = "path1" + $_.Name
$newName = "path1" + "$($_.BaseName)_$stamp$($_.Extension)"
Copy-Item -Path $_.FullName -Destination $newName
$count = $count + 1
}
if($count -gt 0)
{
write-host 'Statistic.FileMonitor:' $count;
write-host "Message.FileMonitor: $count file found and moved, Filenames- $msg"
exit 0
}
else
{
write-host 'Statistic.FileMonitor:' $count;
write-host "Message.FileMonitor: $count files found, Filenames- $msg"
exit 0
}
When execution mode is set as Local Host. It execute. But it says no file found. Eventhough file exist under path1
When execution mode is seet as Remote. I am getting result as Down

Related

PowerShell - copying multiple files

I've written a PowerShell script to copy new files across to a shared folder on a server.
I am wondering if there is a way that after I get the list of new files in the sub folders, I can copy them over together - other than using for-each and copying them one at a time - so that I can add a progress bar.
something like this could be a starting point
# define source and destination folders
$source = 'C:\temp\music'
$dest = 'C:\temp\new'
# get all files in source (not empty directories)
$files = Get-ChildItem $source -Recurse -File
$index = 0
$total = $files.Count
$starttime = $lasttime = Get-Date
$results = $files | % {
$index++
$currtime = (Get-Date) - $starttime
$avg = $currtime.TotalSeconds / $index
$last = ((Get-Date) - $lasttime).TotalSeconds
$left = $total - $index
$WrPrgParam = #{
Activity = (
"Copying files $(Get-Date -f s)",
"Total: $($currtime -replace '\..*')",
"Avg: $('{0:N2}' -f $avg)",
"Last: $('{0:N2}' -f $last)",
"ETA: $('{0:N2}' -f ($avg * $left / 60))",
"min ($([string](Get-Date).AddSeconds($avg*$left) -replace '^.* '))"
) -join ' '
Status = "$index of $total ($left left) [$('{0:N2}' -f ($index / $total * 100))%]"
CurrentOperation = "File: $_"
PercentComplete = ($index/$total)*100
}
Write-Progress #WrPrgParam
$lasttime = Get-Date
# build destination path for this file
$destdir = Join-Path $dest $($(Split-Path $_.fullname) -replace [regex]::Escape($source))
# if it doesn't exist, create it
if (!(Test-Path $destdir)) {
$null = md $destdir
}
# if the file.txt already exists, rename it to file-1.txt and so on
$num = 1
$base = $_.basename
$ext = $_.extension
$newname = Join-Path $destdir "$base$ext"
while (Test-Path $newname) {
$newname = Join-Path $destdir "$base-$num$ext"
$num++
}
# log the source and destination files to the $results variable
Write-Output $([pscustomobject]#{
SourceFile = $_.fullname
DestFile = $newname
})
# finally, copy the file to its new location
copy $_.fullname $newname
}
# export a list of source files
$results | Export-Csv c:\temp\copylog.csv -NoTypeInformation
NOTE: that will show progress for total files regardless of size. ex: you have 2 files, one is 1 mb and the other is 50 mb. when the first file is copied, progress will be 50% because half the files are copied. if you want progress by total bytes, i highly recommend giving this function a try. just give it a source and destination. works when given a single file or a whole folder to copy
https://github.com/gangstanthony/PowerShell/blob/master/Copy-File.ps1
screenshot: http://i.imgur.com/hT8yoUm.jpg

Custom Log File Creation - Powershell

I have the following requirement for a script:
a. Get the Scripts Name and Path.
b. Create a ScriptPath\Log-Time|date\Logfile.Log
c. Give the user 3 options, depending on the input update the log file.
For the above requirement ive created the following script:
#Variables Declaration-------------------------------------------
$pat = Split-Path $script:MyInvocation.MyCommand.Path -parent
$LogTime = Get-Date -Format "MM-dd-yyyy_hh-mm-ss"
$a = "[Info]:"+$LogTime+" Logged into Server"
$b = "[Warning]:"+$LogTime+" Unauthorized Access"
$c = "[Error]:"+$LogTime+" Wrong Credentials"
$ScriptName = $MyInvocation.MyCommand.Name
$path = $pat
#Folder and Log Creation------------------------------------------
if([IO.Directory]::Exists($path))
{
$m = New-Item -ItemType directory -Path $path -name Log
$n = New-Item -ItemType directory -Path $m -name $LogTime
}
$LogName = $ScriptName+"_Log_"+$LogTime+".log"
$log = New-Item -ItemType file -path $n -name $LogName
# Log Function------------------------------------------------------
log($in)
function log
{
$in = Read-Host "Enter your Option"
if ($in -eq "0")
{
$latest = Get-ChildItem -Path $n | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$p = $path+$latest.name
Add-Content $p -value $a
}
elseif ($in -eq "1")
{
$latest = Get-ChildItem -Path $n | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$p = $path+$latest.name
Add-Content $p -value $b
}
elseif ($in -eq "2")
{
$latest = Get-ChildItem -Path $n | Sort-Object LastAccessTime -Descending | Select-Object -First 1
$p = $path+$latest.name
Add-Content $p -value $c
}
else
{
$o = "Invalid Input"
$o
}
Move-Item $p $n
}
Whenever i run this, i get two logfiles created.
Exec2.ps1_Log_04-04-2014_10-21-11.log &&&&
MExec2.ps1_Log_04-04-2014_10-21-11.log [M is the folder where the script is run]
and the first log file is empty while the second one contains the text.
Could anyone please help me fix this? and if possible make the script short and sweet somehow?
Thanks and Regards,
Kain
Some of your code seemed redundant, so I removed some. Such as defining $pat and then duplicating it into $path so I just defined $path once. I got rid of $a, $b, and $c since you can just as easily enter the value directly.
Then I got rid of the whole get the latest file in the log folder, and just added the content to the log file defined earlier. I changed the log entries so they were done by tabs so the entry type, date, and the actual entry all line up nicely when you view the log file.
Lastly I changed the whole If>ElseIf>ElseIf thing into a Switch, because Switch is awesome and totally underused! Oh yeah, I got rid of $o = "Invalid Input"; $o because it's pointless to define a variable and then just echo it. What you could do is in the default section have it write-host the error and call the log function again, so people are forced to enter a valid entry.
#Variables Declaration-------------------------------------------
$path = Split-Path $script:MyInvocation.MyCommand.Path -parent
$LogTime = Get-Date -Format "MM-dd-yyyy_hh-mm-ss"
$ScriptName = $MyInvocation.MyCommand.Name
#Folder and Log Creation------------------------------------------
$m = New-Item -ItemType directory -Path $path -name Log
$n = New-Item -ItemType directory -Path $m -name $LogTime
$LogName = $ScriptName+"_Log_"+$LogTime+".log"
$log = New-Item -ItemType file -path $n -name $LogName
# Log Function------------------------------------------------------
log
function log{
$in = Read-Host "Enter your Option (0,1,2)"
Switch ($in){
0 {Add-Content $log -value ("[Info]:`t`t" + $LogTime + "`tLogged into Server")}
1 {Add-Content $log -value ("[Warning]:`t" + $LogTime + "`tUnauthorized Access")}
2 {Add-Content $log -value ("[Error]:`t" + $LogTime + "`tWrong Credentials")}
default {Write-Output "Invalid Input"}
}
}

Powershell Copying Files Script

I am trying to copy, and rename multiple files to miltiple folders. The folders will be labeled sequentially like the files. For example I need to copy Reports.txt change the name to Reports_NW01_20120219.txt to a folder called NW01 then the same process for NW02-NW18. The folder and file names increase by 1. I am new to powershell so please spare me. I have pasted what I have below. I am attempting to read in the date and then append it to the file name. I am at a complete loss now. So any help is appreciated:
$date = read-host "Enter date of the report YYYYMMDD"
write-host $date
for ($Counter = 1; $Counter -le 1; $Counter++)
{
#Destination for files
$DropDirectory = "C:\Users\dh0520\Documents\Powershell Staging\"
#Current Location of the files
$file = Get-ChildItem -Path "C:\Users\dh0520\Documents\Powershell Test\NW01\Reports.txt"
if ($Counter -lt 10) {
$Destination = $DropDirectory+'NW0' + $Counter
$file = Get-ChildItem -Path "C:\Users\dh0520\Documents\Powershell Test\NW0" + $Counter + "\Reports.txt"
Copy-Item $file.FullName ($Destination + $file.BaseName + "_NW0" + $Counter + "_" + $date +".txt")
}
If ($Counter -ge 10) {
$Destination = $DropDirectory+'NW' + $Counter
$file = Get-ChildItem -Path "C:\Users\dh0520\Documents\Powershell Test\NW" + $Counter + "\Reports.txt"
Copy-Item $file.FullName ($Destination + $file.BaseName + "_NW" + $Counter + "_" + $date +".txt")
}
}
I assume you are getting errors with the get-childItem. It is because you cant build the path like that. Try it this way:
$file = Get-ChildItem -Path "C:\test\NW0$($Counter)\Reports.txt"
and this way:
$file = Get-ChildItem -Path "C:\test\NW$($Counter)\Reports.txt"

Import CSV issue powershell

I am working on a script to automate adding users. I want to read from all CSV files in a directory until they are done and then I want to move those csvs to an archive. In the program I am checking a txt file to make sure another instance of the program is not already running. after that I am allowing the code to run or the program to end. When I run the program with 1 or two test files named test.csv and test2.csv I am not having any errors. Once I add random names .csv and try to run these through I am getting the error that import-csv cannot find the file and the path is is telling me the file at it no correct, its from the location of the script.
Here is my code:
$fileDirectory = "c:\test";
$CheckRun = Get-Content c:\test\checkrun.txt
Write-Host $($CheckRun)
if($CheckRun -eq "notrunning") {
Get-ChildItem $fileDirectory -Filter *.csv | Foreach-Object {
$list= Import-Csv $_
$State = "running"
$basename = $_.BaseName
$file = $FileDirectory + "\" + $basename + ".csv"
$ArchiveFile = $fileDirectory + "\archive\" + $basename + "old.csv"
foreach ($entry in $list) {
# will run command here using the entries from the CSVs
write-Host $($entry.EMAIL) $($entry.FIRSTNAME) $($entry.LASTNAME) $($entry.PASSWORD)
}
Move-Item $($file) ${ArchiveFile} -force
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
$State > c:\test\Checkrun.txt
}
$State = "notrunning"
$State > c:\test\Checkrun.txt
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
else {
Write-Host "Press any key to continue ..."
$x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
exit
}
When you get the child items you are getting a file object. Try referenceing the fullname instead it workd for me:
Get-ChildItem $fileDirectory -Filter *.csv | Foreach-Object {
$list= Import-Csv $_.fullname
Otherwise it is trying to look in the path that you are running the script for the file instead of C:\test\filename.csv

Piped dir within Foreach

I'm writing a script to delete pdf files older than 6 months in folder with the 'Email' prefix.
However, my second dir command within my foreach never runs, its code is blocked.
$Now = Get-Date;
$DaysTillDelete = "180";
$LastWrite = $Now.AddDays(-$DaysTillDelete);
$TargetFolder = "C:\Test EMDATA\EMDATA\";
$BackupPath = "\\SHPFS02\IT\EmPower Old";
$EmailFolders = #();
if(-Not(Test-Path -path ($TargetFolder + "\OldFiles" ))) {
mkdir -p ($TargetFolder +"\OldFiles");
}
$Network = Test-Path $BackupPath
#New-PSDrive -Name O -PSProvider FileSystem -Root "$BackupPath"; #-Credential $cred
Write-Host "Running Script"
dir $TargetFolder | %{
# Only delete files with the Email prefix
$name = $_.Name;
if ($_.Name.Length -le 5) {return;}
$id = $_.Name.SubString(0,5);
if ($id -eq "Email")
{
Write-Host "Found slip folder"
$EmailFolders += $TargetFolder + $_;
}
}
ForEach ($folder in $EmailFolders)
{
Write-Host $folder;
dir -path $folder -include *.pdf | %{
Write-Host "Checking" $name;
# Only select files older than 6 months
if( $_.LastWriteTime -le "$LastWrite")
{
$activeItem = Get-Item $TargetFolder + $_;
#Move files into oldfiles
Write-Host $TargetFolder
move-item -path $activeItem -destination ($TargetFolder + "OldFiles\");
if ($Network)
{
move-item -path $activeItem -destination "O:\";
}
Write-Host $_;
remove-item $activeItem;
Write-Host "Deleting" + $name;
}
}
}
The script works till line 31 but doesn't continue on past line 32 and being a fairly beginner PS user I can't see why.
Only use -include with the -recurse parameter.
http://technet.microsoft.com/en-us/library/hh849800.aspx
The Include parameter is effective only when the command includes the
Recurse parameter or the path leads to the contents of a directory,
such as C:\Windows*, where the wildcard character specifies the
contents of the C:\Windows directory.
What you want instead is the -filter parameter:
dir -path $folder -filter *.pdf