Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all 15028 articles
Browse latest View live

Very new to Scripting, Trying to get this macro to work.

$
0
0

I have probably got this all wrong.

This Macro runs in Excel.

It allows me to save the file.

But it will not work for another other use who has access to this file.

I know it is down to the Users\David.Murray, what I need is to able to amend The Path Variable

Sub Create_TimeSlot_View()
' This copies and sorts the DATA from FSC.XLSM to from the Daily FSC, which is sent out each day.
Application.DisplayAlerts = False
Application.ScreenUpdating = False
    
    Columns("L:KO").Select
    Selection.EntireColumn.Hidden = True
    If ActiveSheet.AutoFilterMode Then Cells.AutoFilter
    
Dim Year1 As Integer
Year1 = DatePart("yyyy", Date)
Month1 = DatePart("M", Date)
Day1 = DatePart("D", Date)
CurrentDate = Day1 & "-" & Month1 & "-" & Year1

 ChDir "C:\Users\david.murray\PERFORM GROUP\Change and Release Management - Change Management\FSC Backup"
    ActiveWorkbook.SaveAs Filename:= _
         "C:\Users\david.murray\PERFORM GROUP\Change and Release Management - Change Management\FSC Backup\FSC " & CurrentDate & ".xlsm"
    ChDir "C:\Users\david.murray\PERFORM GROUP\Change and Release Management - Change Management\FSC"
   ActiveWorkbook.SaveAs Filename:= _
      "C:\Users\david.murray\PERFORM GROUP\Change and Relea


Getting users from nested groups.

$
0
0

I have a script that looks at a group and puts the users in an array $Users and loops through and lists them on the screen.  Works great.

Clear-Host
 
$ADGroup = "Intranet Users"
Write-Host "Reading AD users from" $ADGroup
$Users = Get-ADGroupMember $ADGroup | Get-ADUser -Properties * | Select Name,Mail,Department,Enabled

foreach ($user in $Users) {
  Write-Host $User.Name, $User.Mail, $User.Department, $User.Enabled
}

I want to change this to use a group that has several other groups as members that contain users. Example Group:  "All Company Users" that contains "All Illinois Users", "All Florida Users", etc as well as some users.

I just want the username, email, department and if they are enabled.

I need them in an array like $User so I can loop through and compare to another source.

Thanks.

OpenTextFile permission denied

$
0
0

Hello,

I am having issues trying to run the script below, which reads a <g class="gr_ gr_397 gr-alert gr_spell gr_inline_cards gr_disable_anim_appear ContextualSpelling ins-del multiReplace" data-gr-id="397" id="397">csv</g> file into a 2-dimensional array.  The error is thrown here:   Set inCsv    = inCsvSys.OpenTextFile(CSVFile,"1",True)  

This is the error that I get on this line: Permission denied Code:800A0046

Function CSVArray(CSVFile)

  Dim comma, quote
  comma = ","
  quote = Chr(34)

  Dim charPos, charVal

  Dim cellPos, colMax, colNum
  colMax  = -1

  Dim cellArray(), cellComplete, cellQuoted, csvRecord

  Dim inCsvSys, inCsv, inRow(), rowCount
  rowCount     = -1
  Set inCsvSys = CreateObject("Scripting.FileSystemObject")
  Set inCsv    = inCsvSys.OpenTextFile(CSVFile,"1",True)
  Do While Not inCsv.AtEndOfStream
    rowCount = rowCount + 1
    Redim Preserve inRow(rowCount)
    inRow(rowCount) = inCsv.ReadLine
  Loop
  inCsv.Close

  For r = 0 to rowCount

    csvRecord = inRow(r)
    colNum = -1
    charPos = 0
    cellComplete = True

    Do While charPos < Len(csvRecord)

      If (cellComplete = True) Then
        colNum       = colNum + 1
        cellPos      = 0
        cellQuoted   = False
        cellComplete = False
        If colNum > colMax Then
          colMax = colNum
          Redim Preserve cellArray(rowCount,colMax)
        End If              
      End If

      charPos = charPos + 1
      cellPos = cellPos + 1
      charVal = Mid(csvRecord, charPos, 1)
      If (charVal = quote) Then
        If (cellPos = 1) Then
          cellQuoted = True
          charVal    = ""
        Else
          Select Case Mid(csvRecord, charPos+1, 1)
          Case quote
            charPos = charPos + 1
          Case comma
            charPos = charPos + 1
            cellComplete = True
          End Select
        End If
      ElseIf (charVal = comma) And (cellQuoted = False) Then
        cellComplete = True
      End If
      If (cellComplete = False) Then
        cellArray(r,colNum) = cellArray(r,colNum)&charVal
      End If

    Loop

  Next
  CSVArray = cellArray
End Function

               

Obtaining errorlevel return codes in Powershell - Is it possible?

$
0
0

I have see quite a few ways of starting a program, such as 7-zip, from within Powershell.  However, I have not found a way of capturing the return codes from this program.  These are accessible at the command line level in the %errorlevel% variable. 

How do I gain access to the equivalent of %errorlevel% in Powershell.  Is it possible?


[string](0..9|%{[char][int](32+("39826578840055658268").substring(($_*2),2))})-replace "\s{1}\b"

To export Skype for business online users

$
0
0

Hi,

I need PS command to export Skype for Business online users who is having different SIP and email address.

Thanks in Advance.

Regards,
MS


PS Script for Emailing List, Including FindTime

$
0
0

I have a script to send emails to a list of users in a csv, what I'd like to know is if anyone has any ideas on how to include a FindTime invite using PS. Thanks!


Web Page to Run PowerShell Scripts

$
0
0

Have any one created web page to run powershell scripts ??

I have multiple powershell scripts for which i want to create a WebPage so it will be easy for users to run any script as required by them from the webpage.

Please advice if anyone has done this ? IF Yes, Using which technology - HTML/Angular/JS ????


Manvendra Bele

ADSI WinNT get User properties

$
0
0

I want to read Network Access Permission property value of local user account (Local Users and Groups ► Properties ► Dial-in tab) at WS2012r2 in workgroup environment.

I run this vbscript:

OnErrorResumeNextSet usr = GetObject("WinNT://<Workgroup_name>/<computer_name>/<user_name>,user")

WScript.Echo "Parameters "& usr.Parameters
WScript.Echo "RasPermissions "& usr.RasPermissions
WScript.Echo "DialinPrivilege "& usr.DialinPrivilege
WScript.Echo "msNPAllowDialin "& usr.msNPAllowDialin

WScript.Echo "MaxDisconnectionTime "& usr.MaxDisconnectionTime

and get only:

Parameters m                     d                              P♣▲∟☺msNPAllowDi
alin?????????????☺CtxCfgPresent????☺CtxCfgFlags1????☺CtxShadow????*☻☺CtxMinEncry
ptionLevel?
MaxDisconnectionTime 60

— just msNPAllowDialin mentioned in Parameters string value, but in unreadable form.

How can I accomplish this?


Convert excel (.xlsx) file to csv file using Vbscript

$
0
0

Hi,

I am want code for converting the excel (.xlsx) file to CSV file using vbscript.

Thanks in advance.

Issues properly formatting SMTPEventConsumer message body in PowerShell

$
0
0

I have a script I am developing to monitor the Win32_PrintJob class on our print servers for jobs over a certain size. Part of the solution involves using the SMTPEventConsumer to fire off an email message. The trouble I am running into is that standard escape characters don't seem to work in my message string. The code snippet is below

$instanceConsumer_SMTP.Message = "Job Owner: %TargetInstance.Owner%`nJob Source: %TargetInstance.HostPrintQueue%`nJob Size(bytes): %TargetInstance.Size% `nJob ID: %TargetInstance.JobID% `nJob Queue: %TargetInstance.Name%"

What is returned in the body of the email is this:

From: WMI@host <WMI@host> Sent: Friday, January 4, 2019 11:08 AM To: notification@contoso.com Subject: Win32_PrintJob: Large Print Job detected Job Owner: employ


What I am expecting is more like:

From: WMI@host <WMI@host> 
Sent: Friday, January 4, 2019 11:08 AM
To: notification@contoso.com
Subject: Win32_PrintJob: Large Print Job detected

Job Owner: employee23
Job Source: ComputerA
Job Size(bytes): 1234459
Job ID: 435
Job Queue: PrinterQ
Any thoughts on what escape sequence might work, or what I am doing wrong with the escape sequences I have used? I have tried many iterations of it with varying amounts of success, but nothing returns quite how I would like. Thanks for any advice!

Disconnect all USB devices

$
0
0

I am not sure if this is the appropriate forum for my question.

I need a CMD script to "Disconnect all USB devices" --> please note "disconnect"not "disable".

Unfortunately i couldn't find "disconnect" parameter to use on devcon (64) but I found this option (below) on USBDeview (Freeware) --> I command line options (listedhere) I was not able to find out the command to disconnect the USB and I was wondering if someone used  or could suggest me this option on devcon or USBDeview.

Thanks 




Hey Scripting Guy, How do I print a powershell script from ISE?

$
0
0

Hey Scripting Guy, How do I print a powershell script from ISE?  If I can't print FROM powershell ISE, Can you write a script that
1) reads a .ps1 file and
2) add line numbers
3) adds simple indenting,
4) colors codes the code
5) Send to default printer

how to call psexec from powershell

$
0
0

I can't get this to work properly without the the initial error,

PS C:\scripts> psexec \\pc01 java -version
PsExec.exe :
At line:1 char:7
+ psexec <<<<  \\pc01 java -version
    + CategoryInfo          : NotSpecified: (:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
 

Tried double quotes etc.

Note that psexec does actually get called and runs ok despite the error above !

any ideas ?

Add/Remove program list in vista

$
0
0
Hello.....

How can i get list of all programs that installed in my computer.
In XP i got all programs list (installed and updated) using registry key (HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\)

but in vista i got only the list of installed program not updated list.how can i get that updated program list also?

Please help me....

How can we stop Ransom:Win32/WannaCrypt malware spread?

$
0
0

Hi, Guys.

How can we stop Ransom:Win32/WannaCrypt malware spread? As you know, this malware has worm functionality which attempts to infect unpatched outdated Windows machines. 

Yes, there are good AVs which can detect and quarantine this threat. If we receive multiple ransomware detections reported by our AV, how can we track down instead the infected system which spreads the malware to other vulnerable computers? Assuming this infected system was not detected by our AV for some reason (i.e. AV was not installed)

I can see an article states that the threat creates a service named mssecsvc2.0, whose function is to exploit the SMB vulnerability in other computers accessible from the infected system.

How can we track endpoints also that has this mssecsvc2.0 service running on them via powershell script? Thank you


PowerShell file copy with optional GUI

$
0
0

Hey All,

I've just started a new job and although I'm a SQL DBA and have been for a while I am a complete newb with ps. Infact I have less then a weeks worth of experience!

Below is a ps script that we use here to copy recent backups around; I understand it enough to read it but would like more control over the destination, age of file and maybe dare I say it, even an app-like front-end.

Is this possible and can anyone help me out or point me in the right-direction?

TIA.

#
#
#   Script to archive files 
#   

[CmdletBinding(SupportsShouldProcess=$true)]
Param (
    [Parameter(Mandatory=$true)]        
        [string]    $SourcePath,
    [Parameter(Mandatory=$true)]        
        [string]    $ArchivePath,
    [Parameter(Mandatory=$false)]
        [string]    $Match                  = '',
    [Parameter(Mandatory=$false)] 
    [ValidateSet('All','None','Newer','Larger')]    
        [string]    $OverwriteExisting      = 'Never',
    [Parameter(Mandatory=$false)]
        [switch]      $Remove                 = $false
)

Try {

    If (!(Test-Path $SourcePath -PathType Container)) {
        Write-Error ($SourcePath + ' is not a directory');
        Exit 1;
    }

    if (!(Test-Path $ArchivePath -PathType Container)) {
        Write-Error ($ArchivePath + ' is not a directory');
        Exit 1;
    }

    Get-ChildItem -File $SourcePath | 
		Where-Object { $_.Name -match $Match } | 
		ForEach-Object {

        $sizes = @{}; $times = @{};
        
        $sourceFile = $_; 
        $archiveFile = Get-ChildItem ($ArchivePath + '\' + $_.Name) -ErrorAction SilentlyContinue;

        $overwrite = $false;

        if (('All','None').Contains($OverwriteExisting)) {
            $overwrite = ($OverwriteExisting -eq 'All');
        }
        elseif ($archiveFile) {
            $sizes['source'] = $sourceFile.Length;
            $sizes['archive'] = $archiveFile.Length;
            $times['source'] = $sourceFile.LastWriteTime;
            $times['archive'] = $archiveFile.LastWriteTime;
            $larger = ($sizes['source'] -gt $sizes['archive']);
            $newer = ($times['source'] -gt $times['archive']);

            if ($larger -and $OverwriteExisting -eq 'Larger') {
                $overwrite = $true;
                Write-Verbose ($_.Name + ': source is larger than archive');
            }
            if ($newer -and $OverwriteExisting -eq 'Newer') {
                $overwrite = $true;
                Write-Verbose ($_.Name + ': source is newer than archive');
            }

        }

        if ((!$archiveFile) -or $overwrite) {
            Write-Verbose ('Archiving ' + $sourceFile + ' to ' + $ArchivePath);
            Copy-Item -Force -Path $sourceFile.FullName -Destination $ArchivePath;
            if ($Remove) {
                Write-Verbose ('Removing ' + $sourceFile);
                Remove-Item -Force $sourceFile.FullName;
            }
        }
    }
}

Catch {
    Write-Error $_;
    Exit 1;
}

Powershel Get-Service sometimes no replying

$
0
0

We are using a recurring supervision tool checking the presence of 93 services distributed on 60+ machines.

This works very fine each quarter of an hour.

However sometimes (typically once a week) we got some no_reply, even after a retry.

The syntax is simple (embedded in a batch):

powershell get-service -ComputerName ^%1 -Name ^'%2' | findstr Running

Any idea why a get-service command could fail to reply ?

Regards

WMI Query to return Firewall State

$
0
0
Hi, is it possible please to use WMI to query the NLM/Firewall policy applied to network connections - i.e. is it Domain, Public, or Private? Ive been hunting around for something that will run equally well on Win7 and Win10 devices please. Thank you.

Phil

Hide Drive Script

$
0
0

Hello,

I need a script to hide a windows drive, I already did some tests but

didn´t work...does anyone can help ?

regards


Copy files to a remote server(s) as job.

$
0
0

Hi.

To copy files from client to server machine as job I've tried script like this:

$remote_session = New-PSSession -ComputerName server_1 -Credential user_name
Start-Job -ScriptBlock {
Get-ChildItem -Path c:\folder_src -Recurse |
Copy-Item -Destination c:\folder_dst -ToSession $remote_session }

But when I use receive-job cmdlet - there is an error, informing, that$remote_session variable is not found

in the ScriptBlock of the Start-Job cmdlet.

Here is the text of the error:

Cannot validate argument on parameter 'ToSession'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.+ CategoryInfo          : InvalidData: (:) [Copy-Item], ParameterBindingValidationException+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.CopyItemC
   ommand+ PSComputerName        : localhost

The following version works in case I use receive-job cmdlet to provide the password:

Start-Job -ScriptBlock {
$remote_session = New-PSSession -ComputerName server_1 -Credential user_name
Get-ChildItem -Path c:\folder_src -Recurse |
Copy-Item -Destination c:\folder_dst -ToSession $remote_session 

There might be something with the scope of $remote_session variable.

Tried to make it global, same results.

Is there any solution?

Viewing all 15028 articles
Browse latest View live


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