Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all 6937 articles
Browse latest View live

How can I add date stamp in file name in recursive For-Each object loop?

$
0
0

Requirements:

Folder structure : Reports>Reports A>Prior Periods

                                                           >Report (XLS,ZIP,PDF etc)

                            Reports>  Reports B>Prior Periods

                                                           >Report (XLS,ZIP,PDF etc) and so on..

Everymonth (BD 1 to 5) I need to move Report into Prior Period>yyyyMM(created dynamically where MM will be current month -2..so for e.g If I move reports on April 1, 2015 the folder will be 201502). I have got this far. Now, what i want is to rename Report with yyyyMM(201502) appended to file name while moving in Prior Periods>201502. Here is what I have done so far.

P.S. This is my first attempt learning powershell by trial and error. The code is pieces stiched together from different sources to work plus plugged in trials i did. Please, guide if there is redundant code in it.

param(
 
    [Parameter(
 
        Mandatory = $true,
 
        Position = 0,
 
        HelpMessage = "Root of the folders or share to archive"
       
 
    )]
 
    [String] $source,
 

 
 
    [Parameter(
 
        Mandatory = $false,
 
        Position = 1
 
    )]
 
    [int] $days = 32

)

 

$currentDate = [datetime]::Now
$currentDay = $currentDate.Day
$PreviousMonthEndDate = Get-Date $currentDate.AddDays(-$currentDay*2) -Hour 11 -Minute 59 -Second 59; # go back two months' end date
[string]$Target=$Source+'\Prior Periods\'+$PreviousMonthEndDate.ToString("yyyyMM");

if(!(Test-Path -Path $Target )){
    New-Item -ItemType directory -Path $Target
   
};
Z:\ProdRef\Reports\SAGBBH~1


# Get all the files from the source path, that are not shortcuts and older than the days set
Get-ChildItem $source -Exclude "Prior Periods"  -Recurse |  

         Where {$_.FullName -notlike "*\Prior Periods*" |      #Trying to exclude History folder from the list of directories.
 

         ForEach-Object {
 
# For each file build the destination path 
         

                $dest = $_.fullname -replace ([regex]::escape($source)), ($Target) }
# Check if the destination file path has the parent directory, if not create it
 
                $parent = split-path $dest 

                if(!(test-path $parent)){
 
                    [void] (new-item -Path (split-path $parent) -Name (split-path $parent -leaf) -ItemType directory)
                   


}

               
# Try to move the file into the destination
 
                Move-Item -Path $_.fullname -Destination ($Target) -force  }

Executing this file as C:\Sheelscr\ReportArch.ps1  -source C:\Reports\ReportA; C:\Sheelscr\ReportArch.ps1 -source C:\Reports\ReportB; and so on..

Any help would be greatly appreciated.

 

 


Remote Shutdown Datacore System

$
0
0

Hey guys,

I actually have a problem with writing a Script to shutdown a Datacore Server.
First of all I have to say I even started writing Scripts for Powershell.

So I don't really understand all the "functions" of Powershell Scripting.
Because of that I ask for your help because learning by doing didn't solve my Problem.

Here is the Problem:
In case of a Powerfailure we want to shut down the Servers smoothly.

In a normal case of Maintenance we connect remote to the Server and do the following Tasks:
Connect remote to the Datacore Server
Open the SANsymphonie Console and stop the Datacore Service
Afterwards we can shut down or restart the Server.
When the Server comes up again we restart the Datacore Service and the Mirroring is done in a few Seconds.

For this SANsymphonie offers a Skript which opens imports the Commandlets for Datacore (RegisterDcsCmdlets.ps1).
In PS you are afterwards can connect to the Datacore Server

Connect-DcsServer -Server <Servername> -UserName <User> -Password <myPassword> -Connection SSV1Connect

and stop the Service

(Stop-DcsServer -Server <Servername>)

This works!


What I want to do is to do these Steps in one PS1 which afterwards also shuts down the Server.

How can I do that?


Kind regards
André

Here the content of RegisterDcsCmdlets.ps1

param([ScriptBlock]$scriptBlock, [switch]$forceExit, [string[]]$params)

$configurationPath = $Env:TEMP | Join-Path -ChildPath ([Guid]::NewGuid())
New-Item -Path $configurationPath -ItemType Container > $null
@"
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup useLegacyV2RuntimeActivationPolicy="true">
        <supportedRuntime version="v4.0"/>
        <supportedRuntime version="v2.0.50727" />
    </startup>
</configuration>
"@ | Set-Content -Path $configurationPath\powershell.exe.activation_config -Encoding UTF8

$envVariableName = 'COMPLUS_ApplicationMigrationRuntimeActivationConfigPath'
$envVariableOld = [Environment]::GetEnvironmentVariable($envVariableName)
[Environment]::SetEnvironmentVariable($envVariableName, $configurationPath)

$importCmdletBlock = {
 $bpKey = 'BaseProductKey'
     $regKey = get-Item "HKLM:\Software\DataCore\Executive"
     $strProductKey = $regKey.getValue($bpKey)
     $regKey = get-Item "HKLM:\$strProductKey"
     $installPath = $regKey.getValue('InstallPath')
 
 Import-Module "$installPath\DataCore.Executive.Cmdlets.dll" -DisableNameChecking -ErrorAction Stop
 Write-Host "Successfully registered SANsymphony-V Cmdlets for Windows PowerShell."
}

try
{
    Cls
}
catch
{
    # Nothing to do. This will throw an exception only when it is called
    # without a console.
}

try
{
 if ($scriptBlock -ne $null)
 {
  $finalBlockString = $importCmdletBlock.ToString() + "`n" + $scriptBlock.ToString()
  $finalBlock = [scriptblock]::Create($finalBlockString)

  if ($forceExit)
  { & powershell.exe -Command $finalBlock -args $params}
  else
  { & powershell.exe -NoExit -Command $finalBlock -args $params }
 }
 else
 {
  & powershell.exe -Command $importCmdletBlock -NoExit
 }
}
finally
{
    [Environment]::SetEnvironmentVariable($envVariableName, $envVariableOld)
    $configurationPath | Remove-Item -Recurse
}

Help with a line of code

$
0
0

I got this snippet of code from another script that someone had written.  I have a script that emails managers of users who have not logged on recently to ask where they are and I wanted to put the number of days since they last logged in.

 

$Numberod=Get-ADUsercadcscw-PropertiesLastLogon|Select-object @{E={$($(Get-Date) - $([DateTime]::FromFileTime($_.LastLogon))).Days}}

 

write-host"Not logged in for $Numberod Days"

 

PS U:\> C:\scripts\GetDaysBetween.ps1

Not logged in for @{$($(Get-Date) - $([DateTime]::FromFileTime($_.LastLogon))).Days=128} Days

So I have two things, as you can see from the output I don’t get just 126 for $Numberod I get my whole hash array. I tried -expandproperty but that didn't work.

Second is, I don’t know what this bit is doing (well I do in some sense, it gets the number of days between the last logon and today)

@{E={$($(Get-Date) - $([DateTime]::FromFileTime($_.LastLogon))).Days}}

I know that @{ } encloses a hash table, Get-Date gets the date today and [DateTime] is a .net function, but I don’t know where that .net code is starting and finishing nor what :: does$_.LastLogon is the object I returned with the get-aduser command and piped to the next step

It looks like there is a bit of maths going on in this step

(Get-Date) - $([DateTime]::FromFileTime($_.LastLogon).

I know E is Expression but I’ve not used Expressions before so I’m not familiar with them. There are quite a few $ in there too. 

So if someone could tell what I need to do to get just 126 returned and if they could also explain what is going on I’d appreciate that.

 

Jonathan

Selecting objects in a varaible like $me

$
0
0

If I enter

$me=get-aduserritifjh-PropertiesGivenName,Manager,Surname

How to I reference one of those objects if I wanted a line like

Write-host"My Name is GiveName Surname and my boss is Manager"

 

Thanks

 

Authorization Question

$
0
0

Hi all,

 

i'm really new to powershell and to this forum, so hello to everybody.

I have a  problem which i can' solve, but it sound really simple to me.

In my environment i have a central jumphost. From there is start my PS scripts on the other remote servers.
jumphost: Windows 2012R2
remote servers: Windows 2008R2 with PS v2.0

In these scripts i have an output to a logfile that is located on the jumphost. The hosts are connecting due UNC to the jumphost logfile location.

With this script i just want to test if i can access the logfile location from the remote host:

Invoke-Command -ComputerName $remoteserver -Credential $credentials -ScriptBlock {new-item -ItemType directory \\server\path\to\logs -force}

 

But i got the following error:

Access to the path 'logs' is denied.
    + CategoryInfo          : PermissionDenied: (\\server\path\to\logs:String) [New-Item], UnauthorizedAccessException
    + FullyQualifiedErrorId : CreateDirectoryUnauthorizedAccessError,Microsoft.PowerShell.Commands.NewItemCommand

 

If i run the command "new-item -ItemType directory \\server\path\to\logs -force" on the remote server with the same user, everything is fine

 

May you have any ideas to help me?

 

Regards

 

Oliver

Getting Exception Types that PowerShell might handle

$
0
0

In the traditional try/catch block, you might have something that looks like this:

Try {
#  some dodgy code
}

Catch [<exception 1>] {"exception 2"}
Catch [<exception 1>] {"exception 2"}

Two questions:

1. Where is the set of exceptions that PowerShell can handle documented?

2. Is there some magic incantation to display all the exceptions types in existance?

Getting a piece of information from a complex file

$
0
0

Hi,

wonder if someone can point me in the right direction on this one?...

I have been using invoke-webrequest to get a complex page into a text file. Rightly or wrongly I have decided that once I have the text in a file I am more confident I can do "something" with it.

What I am trying to do is find some text in the file and put into a variable. However the bit I want will change. However the text in front of it does not. So using "select-string" I have found the text before... But I am trying to understand if I can then grab something after what I have selected?

I thought about perhaps reading the whole text into array perhaps but not sure how.. I was thinking of combining this with -split "" to get every single word in the file and then loop through it until I find the text and then use the next piece of text after it..

To explain better (not the actual example)... Say my text file contains the following -

sdsdsd rubbish ksfj ksd tubb rubbish sdjjd dsa sd dsds dasdd dsadd dasdda The result is 5

I am after 5 and have found "The result is "

 

 

 

finding the logon server of remote computer

$
0
0

hello there, I hope someone can guide me on this. I would like to know if there is a command that I can run from the power-shell console that will give me the LOGON SERVER of  the PCs I'm researching without having to remote each PC and interrupt the users. I will then create the script to do this for multiple remote computers. 

I'm doing the following by remote connecting to each PC. I'm looking to get the same results as %logonserver%

example:

c:\> echo %logonserver%

\\DC1

I know there got to be way that I can do this remotely to all the PCs in question. I believe in the power of power-shell Big Smile

Thanks in advanced. 

 


Get-WinEvent - trying to add 'Client Address', 'Computer' and 'Event ID' to output

$
0
0

Hi All

I have the following line of code which checks the security event logs of various servers and puts the date/time, username and source host. I use this to query for events based on a username.

Foreach ($Serverin$S) {$Server; Get-WinEvent-ComputerName$Server-LognameSecurity-FilterXPath"*[System[TimeCreated[timediff(@SystemTime) <= 3600000]] and EventData[Data[@Name='TargetUserName']='$User']]"|Select-ObjectTimeCreated,@{Name='User Name';Expression={$_.Properties[0].Value}},@{Name='Source Host';Expression={$_.Properties[1].Value}} |export-csv-append-path$LogName}

Apologies for the length of line, I'm not sure how I would split this down to make it more readable.

My question is, can anyone help me add:

'client address' - IP address of source

'Computer' - name of computer event is on

'Event Id'

I'm not sure about how to workout the format for an item listed in the 'Select Object'.  I tried using Select-Object * to see if I could workout how to get the item I was looking for but... it didn't workout.

Any help greatly appreciated.

Thanks.

Pete.

Manipulate GUI

$
0
0

I have used a tool called WinBatch in the past to manipulate parts of the Windows GUI.  Example:  Start an app, click on a Menu Option, check a box, press enter.  

Can PowerShell do the same time of stuff?    I've seen where you can create UI dialogs with PS but can you use SendKeys and stuff like that? 

Find Profile Path

$
0
0

HI All,

 I need to find the "Users" folder location from a OU ( Some PC's got C: Drive and Some got D Drive)

I can run $env:USERPROFILE  and check but i need to run from remote and output to a file?

Ex:

Worksation1 -  C:\users\

Worksation 2 - d:\Users\ 

 

As

Not sure which properties I need for this ODBC?

$
0
0

I've been searching for some documentation on what I need to make this work.  I have this script which was orginally intended for SQL.  I am replacing the SQL connection properties with ODBC properties.

My ODBC adapter is not working and I can't find reference to what properties are required. (Select, Connection, etc.)

I have .NET version 4.0.30319 installed.  I noticed different requirements for each version.

Thanks in advance for any guidance.

 

$AttachmentPath = "F:\SQLData.csv"

$SqlQuery = "

SELECT *

FROM table

"

$connectionString = "Driver={PostgreSQL Unicode(x64)};Server=xxxx;Port=xxxx;Database=xxxx;Uid=xxxx;Pwd=xxxx;"

$connection = New-Object System.Data.Odbc.OdbcConnection

$connection.ConnectionString = $connectionString

 

$command = New-Object System.Data.Odbc.OdbcDataAdapter

$command.SelectCommand = $SqlQuery

$command.Connection = $connection

 

$SqlAdapter = New-Object System.Data.Odbc.OdbcConnection

$SqlAdapter.SelectCommand = $command

$DataSet = New-Object System.Data.DataSet

$SqlAdapter.Fill($DataSet)

$connection.Close()

 

$DataSet.Tables[0] | Export-Csv $AttachmentPath

Move profile folder, set end user permissions and update profile path in AD

$
0
0

Hi,

 

I need to move multiple profile folders ("<user account>.V2") from one location to another, set full control permissions per profile folder on the new location for the user account and update the profile path in Active Directory for that user.

 

All based on a list of users (.csv file).

 

Ultimately I'd like to do above with a little logging information and without disrupting end users in their work (checking whether they are logged in?).

 

Can someone please help me with this? I'm still too new to scripting.. Can't figure it out :(

 

Thanks,

 

Jelte

PowerShell Script to Export Users, Groups, and Group Membership

$
0
0

I'm really new to Powershell scripting but am very interested in learning more.  With that said, my boss wants to see if we can write a PowerShell script that exports 100k+ users, groups, and group membership on a nightly basis from multiple domain controllers spread throughout the country.  This NIGHTLY process is essentially an AD replication, but we're limited to SFTP over a private cloud, using text files... so no AD/AD one way replication. 

User info will include SAMAccountName, SID, etc.

Group info will be the same

User/Group membership will be SID/SID relationships.

100k users, nearly that many groups, and who knows how many group membership items we'll find.

Any help will be greatly appreciated.

Thanks for your time. Normal 0 false false false EN-US X-NONE X-NONE MicrosoftInternetExplorer4

 

 

need help - I'm trying to export groups and members of groups from a AD forest

$
0
0
If I run the first part (ending at $Search.FinadAll() ) I get the list of groups that fit the query *PCSupport. But if I runit it fails on the rest of the groups/domains with
Get-ADGroupMember : Cannot find an object with identity: 'CN=PCSupport,OU=Groups,DC=domain2,DC=company,DC=com' under: 'DC=domain1,DC=company,DC=com'.
$forestName= ([System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()).Name
$ADsPath= [ADSI]"GC://$forestName"
$Search=New-ObjectSystem.DirectoryServices.DirectorySearcher($ADsPath)
$Search.Filter="(&(objectCategory=group)(SamAccountName=*PCSupport))"
$Search.FindAll() | ForEach {

$group=$_.Properties.cn
$path=$_.Properties.distinguishedname | Select -Unique

Get-ADGroupMember
-Identity$path |
Select @{N='Group';E={$group}},SamAccountName

} | Sort Group,SamAccountName |
Export-Csv .\groupList.csv-NoTypeInformation

How to ensure the $webClient.DownloadString(url) is really completed (all downloaded)?

$
0
0

Have the following powershell script (v4)

 

$webClient = new-object System.Net.WebClient

$startTime = get-date

$webClient.DownloadString(http://localhost/a.aspx)

$endTime = get-date

($endTime - $startTime).TotalSeconds + " seconds"

 

The question is, how to ensure the $webClient.DownloadString is really completed? I mean, if there is a iframe or sub-call within a.aspx, then how to ensure to capture the $endTime only when everything are completed in that page (a.aspx)?

Thanks.

 

 

Connecting to Linux boxes?

$
0
0

Hi,

As part of the comprehensive server inventory script that i am writing, I realized that it would be great if I can automate the discovery and information gathering of Linux host as well. Is that possible with powershell? I would need to know things like version and edition of the Linux operating system, ram, cpu cores, as well as drive space usage...  I am using Powershell v2.0.

Thank you for your help as always! 

Select Xml node attribute

$
0
0

Hi,

i have the below XML <?xml version="1.0" encoding="utf-8" ?>
<Locations>
  <Location>
    <PreRequisites DownloadPath="DP1" LocalPath=""/>
    <Software DownloadPath ="" LocalPath="">
    </Software>
  </Location>

  <Location>
    <PreRequisites DownloadPath="DP2" LocalPath=""/>
    <Software DownloadPath ="" LocalPath="">
    </Software>
  </Location>
</Locations>

I am trying to loop it and assign each location xml values to variables. But i could not get the value of attributes like DownloadPath.

Below is the script i am testing to fetch the value

 

[xml]$ConfigFile = Get-Content "$MyDir\Myxml.xml"

try
{

   #$ConfigFile.Configurations.Configuration.PreRequisites.DownloadPath
   foreach($config in $ConfigFile.Locations.Location){
       write-Host $config.PreRequisites | Select DownloadPath
      
      
}
  
}
catch
{
   Write-Warning $_.Exception.Message
}

Edit Ini Files

$
0
0

I  wanted to find out if you can help me with a script that will edit .ini files, and update the server name. We have about 1700 ini files. That need to have new print server names since the old server is are going to be decommissioned soon.

The filed that needs to be updated is the Host value. Ie if the Host value is Host = “KBFILE01” it should be update to Host = “vKBprt01”

** The problem that I am having is that instead of the script replace the value in Host it is replacing the whole line.

Before Script:

Printer=SMB2 Local Name="Windows Printer | LB-28-11" Host="KBFILE01" Name="LB-28-11" PrinterID="HP LaserJet 4100 Series PCL6" Class="PCL5" Enabled=yes

I need it to be like :

Printer=SMB2 Local Name="Windows Printer | LB-28-11" Host="vKBprt01" Name="LB-28-11" PrinterID="HP LaserJet 4100 Series PCL6" Class="PCL5" Enabled=yes

Thanks

How can I call a powershell command from another powershell file?

$
0
0

I cannot seem to figure out how to call this command from another powershell file? Any help would be appreciated.

"D:\Program Files\Microsoft\Exchange Server\V15\scripts\RedistributeActiveDatabases.ps1" -dagname "gsdag1" -BalanceDbsByActivationPreference -Confirm:$false;

Viewing all 6937 articles
Browse latest View live