Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

Script to change Scheduled Task to run monthly

$
0
0

I need to change many scheduled tasks to run monthly.

The problem I have is New-ScheduledTaskTrigger does not have a -Monthly switch.

I can create new tasks that run monthly using schtasks.exe, but that does not seem to allow changing triggers if the task already exists.

I'd appreciate any ideas.



Remove-Item Requested registry access is not allowed

$
0
0

Help please,

I have written a Powershell script that is trying to use Remove-Item to delete some Registry keys. I am running under Admin. if I go into Regedit it will let me delete the keys but if I run the Powershell script I get "Remove-Item Requested registry access is not allowed."

I have checked the permissions for the key and it says I have Delete permission. I am using the PowerShell ISE and am on Windows 7. I have tried -Force and -Recurse but makes no difference, neither does reducing UAC to minimum. It also makes no difference if I start PowerShell ISE with Administrator privileges. Why can I delete from within Regedit but not from PowerShell?

Be grateful for some help.

Dave

Set-ADAccountPassword throws The operation failed because of a bad parameter when DN contains * character

$
0
0

I got following error when change password operation performed through powershell. DN name contains * character. How can i change password for testuser. Is there any alternate way to encode DN name. 

PS C:\Users\Administrator> Set-ADAccountPassword -Identity testuser
Please enter the current password for 'CN=testuser,OU=test*userOU,DC=test1,DC=com'
Password: ********
Please enter the desired password for 'CN=testuser,OU=test*userOU,DC=test1,DC=com'
Password: ***********
Repeat Password: ***********
Set-ADAccountPassword : The operation failed because of a bad parameter.
At line:1 char:1
+ Set-ADAccountPassword -Identity testuser
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (testuser:ADAccount) [Set-ADAccountPassword], ADPasswordException
    + FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.SetADAccountPasswo
   rd

I already tried 

$User = [ADSI]"CN=testuser,OU=test*userOU,DC=test1,DC=com"

$dn = $User.distinguishName

Got same error

I already tried

-encodedCommand . got Same error

Unable to set ACL on Remote Registry -Kindly HELP

$
0
0

Hi All,
Tried to set ACL on remote registry but it doesn't work. Tested the same code on local computer which works fine. Please help
objective : Need to assign full permission to "Domain Users" on registry (HKLM\Software\Microsoft) of several remote computers.

Code :
Set-ExecutionPolicy unrestricted -Force
Import-Module -Name psrr -Force

$servers= Get-Content -Path 'D:\ServerList.txt'

foreach($pc in $servers)
{
write-host "Setting ACL Permission for $PC"
$RegSec = new-object system.Security.AccessControl.RegistrySecurity
$rule = New-Object System.Security.AccessControl.RegistryAccessRule("Domain users", "FullControl", "ContainerInherit, ObjectInherit", "None", "Allow")
$RegSec.AddAccessRule($rule)

$RemoteKey = [microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine", $pc)
$RemoteAccess = $RemoteKey.OpenSubKey("Software\Microsoft", $true)

$RemoteAccess.SetAccesscontrol($RegSec)
}

***************

please let me know whats wrong here

This code works well on for the same computer from where this PS run.. but doesn't work for remote computer on same domain.


Get-eventlog not able to list another log files

$
0
0

Hello,

Where is the secret?

Could someone explain why im not able to gather content of Operational log file?

I just see:

But Operational Log file still exist in event viewer?

Also is no propertie? how it can be gathered? Not exist? I have it.

Powershell Script not running correctly in Task Manager

$
0
0

I have a powershell script which runs FSW to monitor a directory into which new files are added.

When I run this script from the desktop, using Powershell running as administrator, it works perfectly.  But when I run the same script in Task Manager as Admin it runs partially but does not appear to see the FSW response when a new file appears in the monitored directory so it does not execute the code to respond to a new file.

I have checked permissions on the relevant folders and granted as much access as possible.

The outlog file containts just the following two lines:

On 08/25/2016 13:53:49 The script is unregistering the File creation event if it exists so that this script can register it..
On 08/25/2016 13:53:49 FSW started monitoring folder C:\Program Files (x86)\TradeStation 9.5\Scans\Strategy Scans\ATM Options Daily Scan.tsscan for the creation of a new scanner output file.

When a new file appears in the directory the script does not respond - though when run in powershell from the desktop it works perfectly...  Steps 1 & 2 execute but Step 3 and subsequent steps do not run.

If anyone can suggest why this may be I would very much appreciate it.

Rapier

The script is as follows:

#By BigTeddy  September 2011 &
# modified by SRJ        May & August  2016
 
#This script uses the .NET FileSystemWatcher class to monitor file events in folder(s). 
#The advantage of this method over using WMI eventing is that this can monitor sub-folders. 
#The -Action parameter can contain any valid Powershell commands.  I have just included two for example. 
# The script can be set to a wildcard filter, and IncludeSubdirectories can be changed to $true. 
# You need not subscribe to all three types of event.  All three are shown for example. 

# Version 2.9
# Modified to address the errors in v2.7 - see the v2.7.txt file for details

# Version 2.11
# Revised to make it clearer how the fsw monitor is working.

# Version 3.o
# Minor amendments to debug operation under task manager.

# ------------------------------------------------------------------------
# Step 1: Unregister the file creation event before loading the new script

$Today = Get-Date

Unregister-Event -SourceIdentifier FileCreated
Write-Host "Unregistering the File creation event if it exists so that this script can register it."
Out-File -FilePath c:\SRJ_ATM\outlog.txt -Append -InputObject "On $Today The script is unregistering the File creation event if it exists so that this script can register it.." 

# -------------------------------------------------------------------------------------
# Step 2 Monitor the scanner output folder for the creation of a new csv files (*.txt). 

$folder = 'C:\Program Files (x86)\TradeStation 9.5\Scans\Strategy Scans\ATM Options Daily Scan.tsscan'
$filter = '*.txt'  

Write-Host "FSW is now monitoring folder $folder for the creation of a new scanner output file."
Out-File -FilePath c:\SRJ_ATM\outlog.txt -Append -InputObject "On $Today FSW started monitoring folder $folder for the creation of a new scanner output file." 
                          
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $false;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'} 
 
# -------------------------------------------------------------------------------------
# Step 3 Register the new file creation event. 

Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action { 

# -----------------------------------------------
# Step 4 When a file is created, do the following

$name = $Event.SourceEventArgs.Name
$changeType = $Event.SourceEventArgs.ChangeType 
$timeStamp = $Event.TimeGenerated
$folder = 'C:\Program Files (x86)\TradeStation 9.5\Scans\Strategy Scans\ATM Options Daily Scan.tsscan'
$Today = Get-Date

Write-Host "FSW has detected a new scanner output file in $folder."
Out-File -FilePath c:\SRJ_ATM\outlog.txt -Append -InputObject "On $Today FSW detected a new scanner output file in $folder." 

# clear the existing scan file
Write-Host "Deleting the existing scanner output file at C:\SRJ_ATM\DailyScan.txt."
Out-File -FilePath c:\SRJ_ATM\outlog.txt -Append -InputObject "On $Today Powershell is deleting the existing scanner output file at C:\SRJ_ATM\DailyScan.txt." 

rm C:\SRJ_ATM\DailyScan.txt -ErrorAction Ignore

Write-Host "The file C:\SRJ_ATM\DailyScan.txt was removed if it existed"
Out-File -FilePath c:\SRJ_ATM\outlog.txt -Append -InputObject "On $Today the file C:\SRJ_ATM\DailyScan.txt was removed if it existed"

# get details of the new file
Write-Host "The file $folder'\'$name was $changeType at $timeStamp" -fore green
Out-File -FilePath c:\SRJ_ATM\outlog.txt -Append -InputObject "On $Today the file $folder\$name was $changeType at $timeStamp" 

# If this is the CSV file store the file name in the $CSVName variable

Write-Host "Verifying that this is the Scanner Output csv file."
Out-File -FilePath c:\SRJ_ATM\outlog.txt -Append -InputObject "On $Today Powershell is verifying that this is the Scanner Output csv file." 

 $csv = $Event.SourceEventArgs.Name.Endswith(".txt")
 if ($csv)

 $CSVName = $Event.SourceEventArgs.Name
 Write-Host "Powershell identified $folder\$CSVName as the scanner output txt file"
 Out-File -FilePath c:\SRJ_ATM\outlog.txt -Append -InputObject "On $Today Powershell identified $folder'\'$CSVName as the scanner output txt file."

 # rename the scanner output file
 Write-Host "Powershell is renaming the scanner output file"
 Out-File -FilePath c:\SRJ_ATM\outlog.txt -Append -InputObject "On $Today Powershell is renaming the scanner output txt file."

 Rename-Item $folder\$CSVname $folder\DailyScan.txt
 Write-Host "The file $folder\$CSVname was renamed to DailyScan.txt" 
 Out-File -FilePath c:\SRJ_ATM\outlog.txt -Append -InputObject "On $Today The file $folder\$CSVname was renamed to DailyScan.txt"

 Write-Host "Move $folder\DailyScan.txt to c:\SRJ_ATM\"
 Out-File -FilePath c:\SRJ_ATM\outlog.txt -Append -InputObject "On $Today the file $folder\DailyScan.txt' is being moved to c:\SRJ_ATM\"

 Move-Item $folder\DailyScan.txt c:\SRJ_ATM\
 
 Write-Host "The file $folder\DailyScan.txt was moved to c:\SRJ_ATM\"
 Out-File -FilePath c:\SRJ_ATM\outlog.txt -Append -InputObject "On $Today the file $folder\DailyScan.txt' was moved to c:\SRJ_ATM"
Out-File -FilePath c:\SRJ_ATM\outlog.txt -Append -InputObject "------------------------------------------------------------------------------------------------------."
 
else {
Write-Host "Powershell determined that $CSVName is NOT a txt file"
Out-File -FilePath c:\SRJ_ATM\outlog.txt -Append -InputObject "On $Today Powershell determined this was not the csv file."
Out-File -FilePath c:\SRJ_ATM\outlog.txt -Append -InputObject "-----------------------------------------------------------------."
 
}


Access denied when using Powershell Sendkeys in Jenkins

$
0
0

I'm using the Windows PowerShell Plugin in Jenkins and want to open my browser and start inputing keystrokes.

When I use the following code in powershell ISE on my computer it works a charm:

Add-Type –AssemblyName System.Windows.Forms
$url = "http://webaddress"
Start-Process -FilePath iexplore -ArgumentList $url
sleep 30
[System.Windows.Forms.SendKeys]::SendWait("{2}{tab}{H}{E}{L}{L}{O}")
sleep 10
[System.Windows.Forms.SendKeys]::SendWait("^{X}")

However, once I use it in Jenkins it returns the following error, telling me my access to the keystrokes is denied.

Started by user admin
Building on master in workspace C:\Program Files\Jenkins\workspace\Jenkins Test
[Jenkins Test] $ powershell.exe -NonInteractive -ExecutionPolicy ByPass "& 'C:\WINDOWS\TEMP\hudson736825107904459976.ps1'"

Exception calling "SendWait" with "1" argument(s): "Access is denied"
At C:\WINDOWS\TEMP\hudson736825107904459976.ps1:11 char:42+ [System.Windows.Forms.SendKeys]::SendWait <<<< ("{2}{tab}{H}{E}{L}{L}{O}")+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException+ FullyQualifiedErrorId : DotNetMethodException


Exception calling "SendWait" with "1" argument(s): "Access is denied"
At C:\WINDOWS\TEMP\hudson736825107904459976.ps1:15 char:42+ [System.Windows.Forms.SendKeys]::SendWait <<<< ("^{X}")+ CategoryInfo          : NotSpecified: (:) [], MethodInvocationException+ FullyQualifiedErrorId : DotNetMethodException


Finished: SUCCESS

I'm using Jenkins as admin so I wouldn't expect there to be issues with permissions. I installed it and setup using the same account on the server too.

Advice?


How to append header upto four columns using powershell in csv file

$
0
0

Hi,

I am novice at powershell scripting and i want to write a script in which I can append Name, FilePath, Specification, DateTime as column headers and export that csv file.

Please anyone can help me out for the same.

Thanks in advance.


Simple script

$
0
0

Hello , 

I'm wondering why when I try to run loop script it doesn't work . For example when I run 

get-wmiobject -computername comp1 win32_startupcommand     - it works 

but when i try something like this :

$comps=get-adcomputer filter * 

foreach ($comp in $comps) {

get-wmiobject -computername $comp wmi32_startupcommand 

}

it doesnt work ... 

any sugesstions ? 

Unable to execute PowerShell script in restricted environment

$
0
0

Hi,

I have a PowerShell script below that failed to execute despite putting the"Set-ExecutionPolicy RemoteSigned -Scope Process -Force" command on top. How can I run the script without levitation in one script?

Set-ExecutionPolicyRemoteSigned-ScopeProcess-Force

$HKEY_Local_Machine=2147483650

$computer='.'

$reg=[WMIClass]"ROOT\DEFAULT:StdRegProv"

$Key    ="SOFTWARE\Microsoft\Internet Explorer"

$ValueName="Build"

$results  =$reg.GetStringValue($HKEY_LOCAL_MACHINE,$Key, $ValueName)

" "

"IE: {0}"-f$results.svalue

 

Select-String from $a variable, is it possible with powershell?

$
0
0

Hello, Guys !

I made simple variable $a to get required event log.

$a=get-winevent-LognameMicrosoft-Windows-TaskScheduler/Operational|Where-Object{$_.ID-eq"200"}|selecttimecreated,ID,Message|ft*-Autosize

So, i got these information, example: Description of message.

26-08-2016 13:39:34 200 Task Scheduler launched action "%windir%\system32\wermgr.exe" in instance "{15F1A2D3-ECAE-4769-A5D5-FBE637BC51EF}" of task "\Microsoft\Windows\Windows Error Reporting\QueueReporting".            

26-08-2016 13:26:41 200 Task Scheduler launched action "Shell Create Object Task Delegate" in instance "{0E2EC646-9D86-49DF-94B8-F467DFFC224C}" of task "\Microsoft\Windows\Shell\CreateObjectTask".                       

26-08-2016 13:26:33 200 Task Scheduler launched action "Certificate Services Client Task Handler" in instance "{E49AF7D7-7094-49CB-B322-0EABE5D36ABB}" of task "\Microsoft\Windows\CertificateServicesClient\UserTask".    

26-08-2016 13:26:33 200 Task Scheduler launched action "Wininet Cache task object" in instance "{65107362-7AFC-47A0-B25E-8B217EF7F6A3}" of task "\Microsoft\Windows\Wininet\CacheTask".                                    

26-08-2016 13:26:33 200 Task Scheduler launched action "MsCtfMonitor task handler" in instance "{CA618350-79DF-4F16-B91F-79F6286868EB}" of task "\Microsoft\Windows\TextServicesFramework\MsCtfMonitor".                   

26-08-2016 13:26:33 200 Task Scheduler launched action "Certificate Services Client Task Handler" in instance "{5B2D55C8-E1C7-424C-8000-4AB335507629}" of task "\Microsoft\Windows\CertificateServicesClient\UserTask".    

26-08-2016 12:40:18 200 Task Scheduler launched action "C:\WINDOWS\system32\sc.exe" in instance "{D3E568EA-0C40-431C-B2A4-BBBC7058CB89}" of task "\Microsoft\Windows\WindowsUpdate\Scheduled Start".                       

26-08-2016 12:40:10 200 Task Scheduler launched action "C:\WINDOWS\system32\sc.exe" in instance "{C678C6FA-037D-4582-8411-C5794FA4F3C6}" of task "\Microsoft\Windows\WindowsUpdate\Scheduled Start With Network".          

26-08-2016 12:15:43 200 Task Scheduler launched action "%windir%\system32\wermgr.exe" in instance "{F2C9A842-89F0-494A-BC07-F1F8990892DA}" of task "\Microsoft\Windows\Windows Error Reporting\QueueReporting".            

26-08-2016 12:02:42 200 Task Scheduler launched action "Certificate Services Client Task Handler" in instance "{B5EBA29E-FBFC-463D-8B6B-7156A0AF0599}" of task "\Microsoft\Windows\CertificateServicesClient\UserTask".    

26-08-2016 12:02:42 200 Task Scheduler launched action "MsCtfMonitor task handler" in instance "{CE33D32D-406D-415F-AA7A-2B14B7601735}" of task "\Microsoft\Windows\TextServicesFramework\MsCtfMonitor".                   

26-08-2016 12:02:42 200 Task Scheduler launched action "Wininet Cache task object" in instance "{E6182B9E-3CCB-4B01-A718-9DEE8B899ECD}" of task "\Microsoft\Windows\Wininet\CacheTask".                                    

26-08-2016 10:43:06 200 Task Scheduler launched action "Certificate Services Client Task Handler" in instance "{00FE4615-EE6A-4257-939B-1F01068568F0}" of task "\Microsoft\Windows\CertificateServicesClient\SystemTask".  

26-08-2016 04:32:25 200 Task Scheduler launched action "C:\WINDOWS\CCM\ccmeval.exe" in instance "{005A53C7-3B6C-4314-96A6-6487E43BD5B1}" of task "\Microsoft\Configuration Manager\Configuration Manager Health Evaluation".

26-08-2016 04:32:25 200 Task Scheduler launched action "" in instance "{476C818C-584A-4D5C-B3FF-D5CBFA814249}" of task "\Microsoft\Windows\.NET Framework\.NET Framework NGEN v4.0.30319 64".                              

26-08-2016 04:32:25 200 Task Scheduler launched action "KernelCeipCustomHandler" in instance "{1EBE29E8-8AB8-4BC9-ABAA-2981EC936506}" of task "\Microsoft\Windows\Customer Experience Improvement Program\KernelCeipTask". 

26-08-2016 04:32:25 200 Task Scheduler launched action "C:\WINDOWS\system32\aitagent.EXE" in instance "{E56001CB-6B98-4829-9AC1-E43D44EABBD9}" of task "\Microsoft\Windows\Application Experience\AitAgent".               

Question

Is it possible to read all the strings from variable $a with message - example: "content validation" and get results just strings with included text “content validation”?

I can not change SID by name

$
0
0

 I can not change SID by name. please help-me

============================================================

D:\SIDlocal.csv

OLD;NEW
S-1-5-21-2824013475-2539778625-3844828982-1019;teste
S-1-5-21-2824013475-2539778625-3844828982-1029;teste - Gravacao
S-1-5-21-2824013475-2539778625-3844828982-1030;teste - Leitura
S-1-5-21-2824013475-2539778625-3844828982-1005;FTP Users
S-1-5-21-2824013475-2539778625-3844828982-1023;Gteste - Leitura
S-1-5-21-2824013475-2539778625-3844828982-1021;GTeste - Escrita
S-1-5-21-2824013475-2539778625-3844828982-1020;GSteste
S-1-5-21-2824013475-2539778625-3844828982-1026;Steste Gravacao

Scrpit PowerShell

==============================================================

$sids = import-csv -Delimiter ";" D:\SIDlocal.csv

foreach ($sid in $sids){
    $old = $sid.OLD
    $new = $sid.'NEW'
    
    gci D:\servicos -recurse | %{
        $acl = get-acl $_.FullName

        $acl.Access | ?{$_.IdentityReference.Value -match $old} |%{
            
            $identity = $_.IdentityReference.Value -replace $old,$new
            $permission = $identity,$_.FileSystemRights,$_.InheritanceFlags,$_.PropagationFlags,$_.AccessControlType
            $aR = New-Object system.security.accesscontrol.filesystemaccessrule $permission
            $acl.RemoveAccessRule($_)
            $acl.SetAccessRule($aR)
        }
        
        $acl | set-acl $_.FullName
    }
}

=======================================================================

Error

Exception calling "SetAccessRule" with "1" argument(s): "Some or all identity references could not be translated."
At C:\TEMP\SID.ps1:16 char:13
+             $acl.SetAccessRule($aR)
+             ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : IdentityNotMappedException


Trying to understand -expandProperty and objects

$
0
0

Lets say i would like to get-process from Ad-computer

get-adcomputer is an object, so in order to return a string needed for get-process i run the following:

Get-ADComputer hostname | Select-Object -ExpandProperty name

which does return s string:

Get-ADComputer hostname | Select-Object -ExpandProperty name | gm

TypeName: System.String

I know get-process is looking for a string on a -computername:

 -ComputerName [<String[]>]

Accept pipeline input?       True (ByPropertyName)

Then why i am getting an error :)

Get-ADComputer hostname | Select-Object -ExpandProperty name | Get-Process

Get-Process : The input object cannot be bound to any parameters for the command 
either because the command does not take pipeline input or the input and its 
properties do not match any of the parameters that take pipeline input.

I know i am missing something very small....

Sharepoint Online add item to list

$
0
0

I am trying to populate fields in a sharepoint list. I am getting back a  couple of errors.

"Cannot call a method on a null value expression" and "Unable to index into an object of type system.string"

#Need to install Microsoft Online Services Sign-in Assistant
#Need to install SharePoint Online Module

#Import the Sharepoint Online module
Import-Module Microsoft.Online.Sharepoint.PowerShell

#Capture administrative credential for future connections.
$creds = Get-credential

#Establishes Online Services connection to SharePoint Online
#Specify tenant admin and site URL
$User = "me@place.com"
$SiteURL = "site_url"
$ListTitle = "Cross-Charge"

#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Context.Credentials = $Creds

#Retrieve lists
$Lists = $Context.Web.Lists
$Context.Load($Lists)
#$Context.ExecuteQuery()

#Import CSV and set variables
Import-Csv C:\CrossCharge.csv | %{
	#Get date
	$date = $_.date
    write-host $date
	#Get site
	$site = $_.site
    write-host $site
	#Get item name
	#Option value RSA 116 YubiKey 115
	$item = $_.item
    write-host $item
	#Get item quantity
	$itemQty = $_.itemQty
    write-host $itemQty
	#Get ticket number
	$ticket = $_.ticket
    write-host $ticket
	#Get username
    $userNT = $_.username
    write-host $userNT
	#Get Cost Center
	$costCenter = $_.costCenter
    write-host $costCenter
	#Get issuing technician
	$tech = $_.tech
    write-host $tech
	}

#Adds an item to the list
$ListItemInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
$Item = $List.AddItem($ListItemInfo)
$Item["Date Required Field"] = "$date"
$Item["Site Required Field"] = "$site"
$Item["Item Name Required Field"] = "$item"
$Item["Item Qty Required Field"] = "$itemQty"
$Item["Ticket # Required Field"] = "$ticket"
$Item["User's NT"] = "$userNT"
$Item["Cost Center Required Field"] = "$costCenter"
$Item["Technician's NT"] = "$tech"
$Item.Update()
$Context.ExecuteQuery()

Get SQL Agent Job EnumHistory via Powershell

$
0
0

Hi guys!!

I  am using Powershell through DollarU (Workload automation software) to execute SQL Agent job (all steps) or one specific step at a time.  So far so good, everything is working!!  However, when it gets to the point where I want to get the History log information, I can't seem get what I want.

Here is my program:  

param ([parameter (Mandatory = $true)][string]$ServerName,

       [parameter (Mandatory = $true)][string]$JobName,

       [string]$StepName = "")



write-host "Starting SQL Agent Job $($JobName) on Server $($ServerName)"

$date=Get-Date

write-host "It is now: $($date)"

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null

$srv = New-Object Microsoft.SqlServer.Management.SMO.Server("$ServerName")

$job = $srv.jobserver.jobs["$JobName"]
$jobstart="No"

if (($job))
{

   if ($StepName -ne '')
      {
        $job.Start($StepName)
        $jobstart="Yes"
        Start-Sleep -s 5  # Pause for 5 seconds (optional) - was 30 seconds (v1); v2=5
      }

   else
      {
        $job.Start()
        $jobstart="Yes"
        Start-Sleep -s 5
      }
}

else
{
   $jobstart="Not found"
}

if ($jobstart -eq "Yes")
{
   write-host "Job $($JobName) on Server $($ServerName) started"
   $i=0

   do
   {
     $job.Refresh();
     $iRem = $i % 5;
     $jobrunning=$job.CurrentRunStatus.ToString();

     if ($iRem -eq 0)
     {
       $date=Get-Date
       write-host "Job $($JobName) Processing--Run Step:$($job.CurrentRunStep) Status:$($job.CurrentRunStatus.ToString())... at $($date)"
     }

     Start-Sleep -s 10; # Pause for 10 seconds  - was 60 seconds (v1); v2=10
     $i++;
   }

   while ($job.CurrentRunStatus.ToString() -ne "Idle")
     if ($job.LastRunOutcome -ne "Cancelled")
     {
       write-host "Job Processing done"
     }
     else
     {
       write-host "Job Processing cancelled/aborted"
     }

     #   $jobRunning="TRUE"
     write-host "$($srv.name) $($job.name)"
     write-host "Last job outcome $($job.LastRunOutcome)"
     write-host "Last job outcome $($job.LastRunDate)"

        if ($job.EnumHistory().Rows[0] -ne $null)
        {
           write-host "xxxx $($job.EnumHistory().Rows[0].Message)"
        }

        if ($job.EnumHistory().Rows[1] -ne $null)
        {
           write-host "yyyyy $($job.EnumHistory().Rows[1].Message)"
        }


        $LastRun=$job.LastRunOutcome

        if ($StepName -ne '')
        {
           $JobStep = $Job.JobSteps[$StepName]
           Write-Host "Name: $($JobStep.Name) RunDate: $($JobStep.LastRunDate) Status: $($JobStep.LastRunOutCome)"
        }

        else
        {
          $StepCount = $job.JobSteps.Count - 1

        for ($i=0;$i -le $StepCount;$i++)
        {
         $m = $job.JobSteps[$i].LastRunDate
         write-host "Name: $($job.JobSteps[$i].Name) RunDate: $($job.JobSteps[$i].LastRunDate) Status: $($job.JobSteps[$i].LastRunOutCome)"

         if ($job.LastRunDate -gt $m)
             {
                   $LastRun="FailedOrAborted"
             }
       }
     }


     if ($LastRun -eq "Failed")
     {
       write-host "Job returned with Failed status"
       exit 2
     }

     if ($LastRun -ne "FailedOrAborted")
     {
       if ($LastRun -ne "Cancelled")
           {
             exit 0
           }

       else
           {
             write-host "Job Cancelled xxxxx"
             exit 3
           }
        }

     else
     {
             write-host "Job Failed or Aborted"
             exit 2
      }
}

else
{
  write-host "Unable to Start Job $($JobName) on Server $($ServerName)"
  write-host "Reason: Job may not exist or not enabled."
  exit 1
}


When there are no specific step to execute...  when only the jobName is provided, I get the proper information.  When it is only a specific step, the second line (YYYY) returns information from past executions.

 if ($job.EnumHistory().Rows[0] -ne $null)
    {
       write-host "xxxx $($job.EnumHistory().Rows[0].Message)"
    }

    if ($job.EnumHistory().Rows[1] -ne $null)
    {
       write-host "yyyyy $($job.EnumHistory().Rows[1].Message)"
    }


In the following picture, you will see the lines of History log information that I got in return for run executed at 10:42 on August 15th (???)

What I would like to get are the following lines of information:

So I tried the following lines of code without any success...

if ($job.EnumJobStepLogs($StepName).Rows[0] -ne $null)
{
  write-host "xxxx $($job.EnumJobStepLogs($StepName).Rows[0].Message)"
}

if ($job.EnumJobStepLogs($StepName).Rows[1] -ne $null)
{
  write-host "yyyyy $($job.EnumJobStepLogs($StepName).Rows[1].Message)"
}

and this...

if ($job.EnumHistory($stepName).Rows[0] -ne $null)
{
   write-host "xxxx $($job.EnumHistory($stepName).Rows[0].Message)"
}

if ($job.EnumHistory($stepName).Rows[1] -ne $null)
{
   write-host "yyyyy $($job.EnumHistory($stepName).Rows[1].Message)"
}

I really don't understand...  and don't know what to try anymore :-(

Can you help me?

Mylene


Mylene Chalut


WARNING: Windows Update for 8/23 breaks PowerShell

Script - Empty folders

$
0
0

Hi,

I would like to write a script to find from when  a folder is empty  and/or  also would like to check if there is no files written to that folder from past 30 mins.

lastwritetime is not good option to select here as it doesn't give accurate result. Is ther a way we can achieve this.

$test = Get-ChildItem -Path "C:\test" -recurse | where-object {$_.name -eq "New folder"} | where-object {$_.lastwritetime -gt (get-date).AddMinutes(-30)} | where-object {$_.PSIsContainer} | Select-Object {$_.Name}
$test1 = ($test | Measure-Object).Count
$test1

create dynamic distribution group based on logon script.

$
0
0

i need to create a distribution group using the custom attributes that will extract all users who belong to a certain logon scrip. currently using this but not working. 

New-DynamicDistributionGroup -Name "SmartStream" -RecipientFilter {(RecipientType -eq 'UserMailbox') -and (scriptpath -eq 'mapsmart.bat')}

Calling one PowerShell Script from Another

$
0
0

Hi,

I am trying to write a PowerShell script that will call another PowerShell script when the first one finishes. Can't get it to work.

1. First script downloads some folders and files from a network share to the users' local C: Drive

2. When the files have finished copying, then fire off another PowerShell script that is part of the files that were copied to the local computer.

    

# Specify the source and destination paths
$Source = "\\SERVER\SHARE$\PSAPPDEPLOY\"
$Destination = "C:\PSAPPDEPLOY"

# Check if the folder exists and if not create it and copy the PSAppDeploymentKit files to the local C: Drive

If (!(Test-Path $Destination)) {

   Copy-Item -Path $Source -Destination $Destination -Recurse

}

Else {
   Write-Host "Directory already exists!"
   Exit
}

$scriptpath = C:\PSAPPDEPLOY\Deploy-Application.ps1

$ArgumentList = -DeploymentType Install - DeployMode Interactive

Invoke-Expression"$scriptPath $argumentList"

Also, is there a way to bypass UAC and get these to fire off without the prompt? I see a way to do it via a batch file, but was hoping to use PowerShell for the whole thing.

Here's a batch file example:

@ECHO OFF
PowerShell.exe -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""C:\PSAPPDEPLOY\Deploy-Application.ps1""' -Verb RunAs}"
PAUSE


setting msExchHideFromAddressLists and ShowinAddressBook

$
0
0

Hello all,

I'm trying to hide Contact objects from the GAL by setting the msExchHideFromAddressLists and ShowinAddressBook attributes, and I'm having a bit of trouble. My code performs a domain search and then attempts to set these 2 attributes on the objects it finds, but this code is not working:

cls

#SET THE QUERY YOU WANT HERE
$SearchFilter = "(&(objectcategory=person)(!useraccountcontrol:1.2.840.113556.1.4.803:=2))"
$SearchDomain = New-Object system.DirectoryServices.DirectoryEntry("LDAP://ou=the shire,ou=middle earth,dc=domain,dc=net")
$Searcher = New-Object System.DirectoryServices.DirectorySearcher
$Searcher.SearchRoot = $SearchDomain
$Searcher.PageSize = 1000
$Searcher.Filter = $SearchFilter
$Searcher.SearchScope = "Subtree"

#SETTING THE PROPERTIES WE WANT RETURNED FOR EACH GROUP.
$PropertyList = "distinguishedname" > $null
foreach ($i in $PropertyList){$Searcher.PropertiesToLoad.Add($i)}

#FINDING ALL THE GROUPS THAT MEET THE $SearchFilter CRITERIA
"Getting search results... Please wait..."
$Results = $Searcher.FindAll()


#LISTING THE RESULTS. IF YOU ARE USING THE $DN -NOTLIKE FILTER HERE, THE $TOTAL VARIABLE
#WILL STILL BE LISTING THE TOTAL NUMBER OF GROUPS FOR THE BASIC SEARCH ABOVE, NOT THE MORE
#GRANULAR SEARCH YOU ARE PERFORMING BELOW.
ForEach($Result in $Results){
    [string]$DN = $Result.Properties.distinguishedname
    get-adobject $DN -pr msexchhidefromaddresslists, showinaddressbook | select name, msexchhidefromaddresslists, showinaddressbook
    set-adobject $DN -replace @{msexchhidefromaddresslists="$true"} -WhatIf
    set-adobject $DN -replace @{showinaddressbook="$null"} -whatif
}

Running this code gives me a "set-adobject: The parameter is incorrect" error on the line where I set the "msExchHideFromAddressLists" attribute.

Running this code gives me a "set-adobject: replace" error on the line where I set the "ShowinAddressBook" attribute.

How can I set these 2 attributes using PowerShell?


Viewing all 21975 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>