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

Add Timestamp - batch file that calls a script CMD

$
0
0

Hello,

I'm having a bugger of a time. I read all these posts about adding a timestamp to a file using batch files and scripts.

What I'm trying to do, Call a batch file which consists of "ftp -i -s:orders.script"

That batch file is called orders.bat

The script is a little different...

Starts off:

Open 192.168.1.5

username

password

cd Client

cd Customer

cd Order

put order.csv order.csv

quit

My question is how do I accomplish putting a timestamp on order.csv that I am putting on the one server from the other?

Do I put it in the script file, or the batch file? Assuming script... Could be wrong though. There has got to be a simple way to do this with how I'm doing this. Or maybe I'm doing it the hard way... Any help would be greatly appreciated. I'm using Command prompt to accomplish this, the batch file is ran from a job in the task scheduler that goes off 3 times a day. the file gets transferred from an SBS 2008 server to an IBM AS400. I hope I'm not missing any information that seems relevant.


PowerShellAccessControl Question

$
0
0

Hello,

We were asked to find a way to check the effective permissions of shares on servers across our environment. I did some research and found the PowerShell Access Control module here: https://gallery.technet.microsoft.com/scriptcenter/PowerShellAccessControl-d3be7b83 

I started playing with it, and thought it would be perfect, specifically the Get-PacEffectiveAccess command. It seemed to get the correct effective permissions on shares for my logged in user, but when I passed it someone who I new shouldn't have access to a share, it came back and said they did.

I re-checked the share, and while the NTFS permissions do not list that account specifically, it does list a group they are in that has explicit Deny on all permissions. If I use the Get-PacEffectiveAccess and specify that group, it does show they have no access. 

So I guess my question is, should the command be taking into account their group membership, or have I misread it?

And does anyone have any other experience doing something similar to try and audit access to shares?

 

Strange with Get-childitem result

$
0
0

Hi, I was using Get-childitem to get all the DLL files inside C:\Windows\System32 folder.

But when I am using below command I am getting nothing,

 
get-childitem -path "C:\Windows\System32" -Include *.dll 

but when I am filtering the files using Select, I am getting the require result.

get-childitem -path "C:\Windows\System32" | where { $_.name -like "*.dll" }
Anyone help, why this is happening

Errors while trying to login to Azure subscription

$
0
0

Hi,

I have 6 subscriptions access (different user accounts) in separate tenants. I would like to get resources details from all subscriptions using PowerShell script.
And I am using below script to authenticate a user and to get access to Azure subscription. The script is working fine for few subscriptions. 
-------------------------------
$useraccount= 'xxxxxxxxxxxxxxxxxxxxxxxxxxx'
$password = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
$AzureSubscriptionID = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

$SecurePassword = ConvertTo-SecureString -AsPlainText $password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $useraccount, $SecurePassword
(Login-AzureRmAccount -Credential $Cred -SubscriptionId $AzureSubscriptionID -ErrorAction Stop) | Out-Null
-------------------------------
And below is the error message for few accounts.
--------------------------------
Login-AzureRmAccount : AADSTS70002: Error validating credentials. AADSTS50126: Invalid username or password
Trace ID: 485faec7-6089-402a-b63a-a608f0584900
Correlation ID: dad46558-700f-4eb4-90cb-f81480c7e7de
Timestamp: 2018-10-16 10:31:02Z: The remote server returned an error: (400) Bad Request.
---------------------------------

Here I am passing the valid Username and password and able to get an access when I use the single command "Login-AzureRmAccount".
But getting the error when trying with the script.

Can someone help me here



How to call another bat file from the run as administrator bat file which will execute as logged in normal user

$
0
0
I have created 2 bat file 
main.bat
normal.bat

main.bat
@echo off
start .NET Framework install.msi
call normal.bat
start anotherinstaller.exe 

The main.bat file runs as administrator. when call normal.bat file from the Administrative command prompt the normal.bat file also execute as administrator. I need to run the normal.bat as logged in user rather then admin privileges. 
Is this possible to run the normal.bat as logged in user in the middle in the main.bat?

PowerShell v5 Install-Script?

$
0
0

I am researching the Install-Script cmdlet in v5 as a possible improvement to a script distribution scheme. Toward that end I have created a local PSRepository and successfully published a script to that repository. When I look in the network share for the repository I can see a .Nupkg file corresponding to my successfully published script. I can also enumerate the published script in the repository with Find-Script.

Now, what can I do with it? I've executed Install-Script, specifying the repository, but have so far been unable to decipher the syntax to execute this installed script. I am assuming I should be able to execute it after installing it...

I am able to run Save-Script to retrieve the script from the repository and have validated that the script it intact and valid.

My searches have not revealed the error of my ways on this one. I suspect I've misunderstood something in this short chain so please illuminate me.

TIA

Find ManagedObjects from user

$
0
0

Hi All

I am trying to find if a particular user is owns any Distribution list as part of the managed objects. I was able to get the list of the DL's the user owns but I am getting the DL with the Distinguished name and i am unable to select only the Distribution List Display Name.

$Managedgrp = Get-ADUser -Identity 'Samaccountname' -Properties managedObjects
Write-Host $Managedgrp
$Groups = $Managedgrp.managedObjects -split(',') | Select-String -Pattern "CN=\"
Write-Host $Groups

I am unable to get the string which starts with CN=\ and I want to trim these characters to get the display name of the DL


Justin

Search-UnifiedAuditLog only returns 90 total records

$
0
0

Hello,

A few weeks back I was able to use Search-UnifiedAuditLog to export to CSV all records up to the maximum of 5000 if I set -ResultSize. Now it doesn't work. No matter what number I choose I can only get 90 total records or less if I choose a number below 90. Is there somewhere that overrides this? 

This is what I'm running

$startDate = (get-date).AddDays(-7).ToString('MM/dd/yyyy')

$endDate = (get-date).ToString('MM/dd/yyyy')

Search-UnifiedAuditLog -ResultSize 5000 -StartDate $startDate -EndDate $endDate -RecordType PowerBIAudit | Export-Csv /path/to/folder 

I'm a global admin on our tenant and I have added myself into the roles required to run that line. It did work but now it has stopped?

Any help on the matter will be much appreciated.

Luke


Set-Acl Set Security Permissions

$
0
0

Hello All,

I am trying to set ACL permissions on per user basis, where I can allow an AD security group to reset password and unlock AD account. I understand that this can be done using delegation but my situation is different and I cannot use that feature.

There use to be an article but its not available anymore https://blogs.technet.microsoft.com/joec/2013/04/25/active-directory-delegation-via-powershell/

I am trying to apply permissions using ACL on AD users. I can read the ACLs using Get-ACL command but I am unsure how to use Set-Acl to apply new permissions. So my question is, in PowerShell how can I set ACL on AD users for a given AD security group? 

Error dending via PS email out our o365 tenant

$
0
0

Hi,

We have a problema qhen try to execute this script via pshell to send an email out of our o365 tenant:

$currentMonth = Get-Date -UFormat %m

$currentMonth = (Get-Culture).DateTimeFormat.GetMonthName($currentMonth)

$credenciales = Import-Clixml -Path '\\localhost\c$\srvadmin\credenciales.xml'

$fecha=$(Get-Date -UFormat "%d-%m-%Y")
$fromaddress = "interno@loquesea.es"
$toaddress = "externo@hotmail.com"
$Subject = "asunto- $currentMonth"


$body = @'
<html> 
  <body>
  </body> 
</html> 
'@

$smtpserver = "smtp.office365.com"
$SmtpPort = '587'
$emailSmtpUser = $credenciales.UserName
$emailSmtpPass = $credenciales.GetNetworkCredential().password

 
$message = new-object System.Net.Mail.MailMessage
$message.From = $fromaddress
$message.To.Add($toaddress) 
$message.Subject = $Subject
$message.body = $body
$message.IsBodyHtml = $true
$smtp = new-object Net.Mail.SmtpClient($smtpserver,$SmtpPort)
$smtp.EnableSsl = $true
$smtp.Credentials = New-Object System.Net.NetworkCredential($emailSmtpUser,$emailSmtpPass)
 
$smtp.Send($message)

Power Shell show these error:

Exception calling "Send" with "1" argument(s): "The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during

MAIL FROM [LNXP265CA0072.GBRP265.PROD.OUTLOOK.COM]"

At line:96 char:1

+ $smtp.Send($message)

+ ~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException

    + FullyQualifiedErrorId : SmtpException

But we use credentials from this script:

$credenciales = Get-Credential

$credenciales.Password | ConvertFrom-SecureString

$credenciales | Export-Clixml -Path C:\srvadmin\credenciales.xml

Some idea of this error?

Regards,


Gerardo,

Use PSEXEC as system account to run a powershell script

$
0
0

Hi, I hope you can help!

I'm trying to write a script which calls psexec as a system account, then, starts powershell as the system account, which is then supposed to run a PS script to install a VPN profile for always on VPN. I can run type in the command manually, and it works, but when I run the bat file, the script returns an error code of 0, but when checking if the the profile is install... it hasn't?

The script I've written is below, how can I get this to pass the PS commands into the psexec posershell window??

@echo off
.\psexec.exe -i -s PowerShell.exe -command {'.\Add VPN.ps1 -xmlFilePath .\Device Tunnel VPN Profile_RemovedTrafficFilter.xml -ProfileName Test_Device_VPN'}

Thanks in advance

How to map drive on separate network without using SMBv1

$
0
0

We have an instance where we need to access a drive on a Windows CE computer on a different network (ie 192.168.2.xxx, or LAN2) than our main LAN (ie 192.168.1.xxx, or LAN1).  In the past we were able to do this with the following script run on the LAN1 PC (Windows 8.1 Pro)  that needed access to the target directory on the LAN2 PC (Windows CE):

LAN1 PC:\> net use w: \\192.168.2.xxx\sharedTargeFolder\sharedTargetSubFolder /user:localUser password /persistent:yes

This allowed the LAN1 PC to see the target folder as a mapped drive ("W" in this case) and  push or pull files to & from the target folder on the LAN2 PC.  The connection did require a firewall rule allowing traffic from the LAN1 PC to the LAN2 PC.  

This worked for a number of years, until we upgraded the LAN1 PC from Windows 8.1 Pro to Windows 10 Pro.  That same script now generates the following error...

You can't connect to the file share because it's not secure. This share requires the obsolete SMB1 protocol, which is unsafe and could expose your system to attack.
Your system requires SMB2 or higher. For more info on resolving this issue, see: https://go.microsoft.com/fwlink/?linkid=852747

Without going backward and enabling SMBv1, what is the best way to re-map the target folder on the Windows Embedded machine on LAN2 to a Windows 10 Pro machine on LAN1?  Thanks in advance for your help.

How to write a Powershell script to replace the specific word of a file and append the same to text file.

$
0
0

I have a txt file which has Database names in a single row. 

I need to write a powershell script that inserts DB names in the text below and appends result to the text file looping everytime. 


BACKUP DATABASE [Database_Name] TO  DISK = N'E:\TempBKP\Database_Name.bak' WITH NOFORMAT, NOINIT, 
 NAME = N'Database_Name-Full Database Backup', SKIP, NOREWIND, NOUNLOAD,  STATS = 10
GO

Compare two arrays with an IF statement

$
0
0

Hi guys, 

I've got a client who grant local administrative rights to the end user workstations by creating an AD security group and adding the user accounts to that group. GPO then publishes the rights to each machine.

All the groups are created in the same name format: group.HOSTNAME_admin

What i've been trying to do is cleanup the old groups and remove any groups for which a machine account no longer exists in AD.

So far all i've gotten this to do is show me "Computer does not exist" on every single line. I know i'm missing something simple here. Eventually the IF statements will move the old groups for which no computer object exists to a temporary 'holding OU' where they will be deleted after 30 days or something. But for now i cannot get it to show me the correct results just to a write-host statement. 

Does anyone have a batter way to compare these two objects?

cls import-module activedirectory $GroupOU = "OU=Workstation Admin Rights,OU=Groups,DC=SOME,DC=DOMAIN,DC=com" $WorkstationOU = "OU=Workstations,DC=SOME,DC=DOMAIN,DC=com" $computers = Get-ADComputer -filter * -SearchBase $WorkstationOU | select Name $Groups = Get-ADGroup -Filter {Name -like "*_Admin"} -SearchBase $GroupOU | select Name | Convert-String -Example "group.HOSTNAME_Admin = HOSTNAME" #Compare the Group names with the Computer objects. If the Group exists but no matching computer object is found, show the orphaned group

Foreach($group in $Groups){

    If ($computers.name -contains $group){
    Write-Host "Computer object exists"
    }
    Else{
    Write-Host "Computer does not exist"
    }
}



Getting members of all DLs (including nested)

$
0
0

Hello, my task is to make a change to all DLs that have 1000 members or less. However, I am running into some challenges:

1. "Get-DistributionGroupMember" does not include a -Recursive parameter to query against all DLs.

2. "Get-ADGroupMember" does have a -Recursive paramater, but I can only query against a single group.

3. Most script examples I have come across is for older versions of Exchange. I am using Hybrid Exchange 2016 with Exchange Online and will be running from Server 2012 R2 Standard.

What methods would you recommend to get started and/or any known examples that I may have missed in my search? Thank you in advance.



Rename Computers using CSV

$
0
0

I wrote this script to rename computers using a CSV and the renaming works but the logging doesn't, the file is empty. Thanks in advance for any hints.

$id = (Get-Credential)

$line ="`r`n"

$logfile = "c:\renamelog.txt"

$success = " successfully changed to "

$fail = " failed to change to "

foreach ($computer in (Import-Csv -Path c:\rename.csv))

{

  Rename-Computer -ComputerName $computer.OldName -NewName $computer.NewName -DomainCredential $id -PassThru -Force

  if ($ComputerChangeInfo.HasSucceeded -eq "True")

  {

    $line | Out-File $logfile

    $computer.OldName | Out-File $logfile

    $success | Out-File $logfile

    $computer.NewName | Out-File $logfile

  }

  elseif ($ComputerChangeInfo.HasSucceeded -eq "False")

  {

    $line | Out-File $logfile

    $computer.OldName | Out-File $logfile

    $fail | Out-File $logfile

    $computer.NewName | Out-File $logfile

  }

}

Read-Host "Press Enter to Exit" 


Errors when getting members of all DLs (including nested)

$
0
0

Hello, I am running into a few errors when running this command to 

1. Get all distribution groups in AD.

2. Count all distribution groups with 1000 members or less (recursively search for nested members)

Get-ADGroup -Filter 'groupcategory -eq "distribution"' 

| Where-Object { ([array](Get-ADGroupMember –identity $_.distinguishedname -Recursive)).Count -lt 1000}

| Measure-Object

Errors:

Get-ADGroup -Filter 'groupcategory -eq "distribution"' 
| Where-Object { ([array](Get-ADGroupMember –identity $_.distinguishedname -Recursive)).Count -lt 1000} 
| Measure-Object

Get-ADGroupMember : An unspecified error has occurred
At line:1 char:82
+ ... ect { ([array](Get-ADGroupMember –identity $_.distinguishedname -Recursive)).Cou ...
+                    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : NotSpecified: 
 [Get-ADGroupMember], ADExce
   on+ FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.GetADGroupMembe

Get-ADGroup : The server has returned the following error: invalid enumeration context.
At line:1 char:1
+ Get-ADGroup -Filter 'groupcategory -eq "distribution"' | Where-Object { ([array] ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : NotSpecified: (:) [Get-ADGroup], ADException+ FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.GetADGroup


Troubleshooting:

- When I run the following I am able to get a count.

(Get-ADGroup -Filter 'groupcategory -eq "distribution"').count

- When I run a "like" filter the command works as well. 

Get-ADGroup -Filter "name -like '*test*'" 

| Where-Object { ([array](Get-ADGroupMember –identity $_.distinguishedname)).Count -gt 3} 

| Measure-Object

I am running this on Exchange Server 2016, Windows Server 2012 R2 Standard

PS version 4.




How to replace the Xml content values using shell script

$
0
0

Can anyone provide me the help to write the shell script to replace the values for below shown xml.

Thank you.

<?xml version='1.0' encoding='UTF-8'?>
<preferences EXTERNAL_XML_VERSION='1.0'>
  <includes>
  </includes> 
  <root type='system'>  
       
        <node name='Controller' >
          <map>
         <entry key='MinimumLargeSize' value='0' />
           <entry key='XMLSchemaVersion' value='3' />
           <entry key='OutputXMLToDisk' value='false' />
         <entry key='OutputBeforeXML' value='false' />
         <entry key='OutputXMLDirectory' value='C:/test/fold1'/>
              
   </map>
  </node>
 </root>
</preferences>

I would like to see as like below
<?xml version='1.0' encoding='UTF-8'?>
<preferences EXTERNAL_XML_VERSION='1.0'>
  <includes>
  </includes>
 
  <root type='system'>
        
        <node name='Controller' >
          <map>
         <entry key='MinimumLargeSize' value='1' />
      <entry key='XMLSchemaVersion' value='4' />
      <entry key='OutputXMLToDisk' value='true' />
      <entry key='OutputBeforeXML' value='true' />
      <entry key='OutputXMLDirectory' value='C:/test/fold2'/>
              
   </map>
  </node>
 </root>
</preferences>

Remote regedit - but edit currently logged in user entries.

$
0
0

So we have a small office setup where 

1. Employees cant regedit  (Gp Restriction) 
2. Remote Registry is on 
3. We have a proxy server which the employees cant toggle on and off (Gp Restriction) 

Issue - every time we make an exception for an employee to NOT use the proxy we remote registry into the system and

HKEY_USERS\S-1-5---blablablasidhere\SOFTWARE\Microsoft\Windows\CurrentVersion\InternetSettings we toggle the proxy on and off as required. 

Can this whole setup we shortened?

tried scripting but regedit has no command line, sid is diff for each user. 

How do we run a proxy value toggle for a remote user who is currently logged in

cant do this via group policy cause the domain functional level <g class="gr_ gr_80 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="80" id="80">isnt</g> high <g class="gr_ gr_81 gr-alert gr_gramm gr_inline_cards gr_run_anim Punctuation multiReplace" data-gr-id="81" id="81">enough.</g> - so there is no alternative route. 


Powershell to create and configure Exclusion settings for Endpoint Protection in SCCM

$
0
0

Hello,

I am just getting started with Powershell and trying to put together a script that creates a custom antimalware policy to exclude specific files and folders from scan. I managed to create a new custom policy but couldn't find a way to explicitly define what files and folders to exclude.

New-CMAntimalwarePolicy -Name "SCEP Custom policy test using PS" -Policy ExclusionSettings -Description "Testing PS way of creating custom antimalware policies"

How do I specify the files and folders I want to exclude in the above command ?

Thanks in advance.


Naga Sai Jonnavithula

Viewing all 15028 articles
Browse latest View live


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