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

File permisson error when doing file sync to a SFTP using winscp assembly

$
0
0

Hi,

I am using winscp .net assembly in powershell for file synchronization with a SFTP server. I am using the following code for synchronization:

http://winscp.net/eng/docs/library_session_synchronizedirectories#powershell

Problem is, when this script sync files through upload to SFTP it generates error, although it actually uploads the file. The script gets terminated immediately with the following error:

------------------------------------------------------

Upload of C:\FileSync\files\test2.txt succeeded
Permissions of /Reports/test2.txt kept with their defaults
Setting timestamp of /Reports/test2.txt failed: WinSCP.SessionRemoteException: Upload of file 'test2.txt' was successful, but error occurred while setting the permissions and/or timestamp.

If the problem persists, turn off setting permissions or preserving timestamp. Alternatively you can turn on 'Ignore permission errors' option. ---> WinSCP.SessionRemoteException: The server does not support the operation.
Error code: 8
Error message from server: SSHServerAPI.SFTP.fxp_attrs
   --- End of inner exception stack trace ---
**Upload of file 'test2.txt' was successful, but error occurred while setting the permissions and/or timestamp.**

If the problem persists, turn off setting permissions or preserving timestamp. Alternatively you can turn on 'Ignore permission errors' option.

------------------------------------------------------

I am not finding any way how to "ignore permission error" as it's suggested in the errors. 

The script does not complain when do the sync through downloading files from SFTP.

Any help please?


Variable does not display on 2nd loop

$
0
0

Hi

I have created a script to query user info. The whole script is to loop, purpose being to choose another user when finished.

all variables are cleared at end of running 1st loop

weird thing is on running the 2nd time/loop all the variables bar 1 show their data/contents.

only below is displayed the 1st run but not the 2nd !

$chosenuser | select name,SamAccountName,LockedOut,PasswordExpired,PasswordLastSet,AccountExpires,emailaddress,DistinguishedName,Created,LastLogonDate,AccountIsDisabled,BadLogonCount,isdeleted,Description,Company,Comment

instead i get {} {} or a blank space.

Any idea why this could be ?

for testing on the 2nd Ioop. I did break the script near the end (before it had a chance to clear the variables) and ran

$chosenuser  and it outputted the correct user from the powershell CLI just fine. so why not then from the script !?

Thanks

Confuseis



Password encrypt in powershell

$
0
0

Hi,

How can i encrypt passwords in a powershell script, then call the powershell script and use the encrypted passwords with sqlplus (oracle utilty) to make a connection to the database?

Thanks.

Problem with mailbox size in powershell

$
0
0

I got problem handling mailbox size in PowerShell.

Since ArchiveQuota is 100G, why does  $quota.ArchiveQuota -eq 100 returned false



No Return Value while using Invoke-Command

$
0
0

Hi,

I am not sure if I am doing the right thing, but I am not getting the desired return value. Below is the code. Can anyone help me in editing it pls.

$ServerIfFoundinADCheck =  Invoke-Command -ComputerName localhost -ScriptBlock  {
Import-module ActiveDirectory 
$tempVar =  Get-ADComputer "test123" 
if ($tempVar -like "Get-ADComputer : Cannot find an object with identity" ) 
        {return $False}
Else 
{return $True}
}

Regards.


Priyabrata

Loop log files to find unique values

$
0
0

Hi

I have a requirement where log files need to be iterated where the url (csuriquery ) = 'IDA=25' and name (csusername) contains '0#.'

This all works but now I need to display a count of unique values for name. How can the working code below be modified ?

# Set the path to the log files
$path = "C:\iisTest"
$DirCounter =0;
# Get a collection of all the log files (anything ending in .log)
$files = Get-ChildItem -Path $path -Filter "*.log"
# Pipe the collection of log files to the ForEach-Object cmdlet
# (the alias of ForEach-Object is %)
$files | %{
    # Call the OpenText method, to return a System.IO.StreamReader object
    $file = $_.OpenText();
    # Record the current line number (to use in the console output)
    $lineNum = 1;
    $FileCounter =0;
    Write-Host "Checking file"$_.Name -f Yellow;
    # Use the EndOfStream method (which returns true when you have reach the end
    # of the file), read each line of the file.
    while($file.EndOfStream -ne $true)
    {
        # Read the next line in the file
        $line = $file.ReadLine();
        if($line -ne $null)
        {

            if($line.Contains("IDA=25") -and $line.Contains("0#."))

            {
                 $line |  Out-File C:\iisTest\filename.txt  -append  -encoding utf8;
                # If the current lines contains a match, write the line number
                # and line text out to the console
               # Write-Host "Line: $lineNum " -NoNewline -ForegroundColor Green;
               #Write-Host "Line: $lineNum " -ForegroundColor Green;
               # Write-Host $line -f Red;
                $DirCounter++;
                $FileCounter++;
            }
        }
        # Increment the line number

        $lineNum++;
    }

     Write-Host $FileCounter;

}
Write-Host "Total in directory- " $DirCounter;


Function to remove all AD groups from user excluding 1 particular group

$
0
0

We have a very long script we use for a user termination process.  One of the functions in the script finds and removes all the groups the account is a member of.  We have had a request that if they are a member of one particular group, that one group not be removed.  This seems like it should be fairly simple to accomplish.

I have tried so many variations and every time it removes the group as well as all the others.

Here is a sample the script that removes all groups that successfully works.:

Function RemoveGroupsFromUser([string]$username)

{

	$userobj = Get-QADUser -Identity $username

	foreach ($grp in $userobj.memberof)

	{

		try

 		{

 			$null = Remove-QADGroupMember -Identity $grp -Member $username -ErrorAction SilentlyContinue

		 }

		catch

 		{

			$ErrorMessage = $_.Exception.Message

			$groupname = $grp.name

			logmessage -user $username -message "Failed to remove user from Group: $groupname"

			Write-Output "Failed to remove $username from $grpname"

		 }

	}

}


This is what I have tried:

ATTEMPT1 - removed all groups including the one we don't want removed.:

Function RemoveGroupsFromUser([string]$username)


{

$userobj = Get-QADUser -Identity $username

foreach ($grp in $userobj.memberof | where {$_.Name -ne "adm_Oracle-Hyperion"})

	{

        	try

                {

                $null = Remove-QADGroupMember -Identity $grp -Member $username -ErrorAction SilentlyContinue

                }

                catch

                {

                $ErrorMessage = $_.Exception.Message

                $groupname = $grp.name

                logmessage -user $username -message "Failed to remove user from Group: $groupname"

                Write-Output "Failed to remove $username from $grpname"

                }

          }

}


ATTEMPT 2 removed all groups including the one we don't want removed.:

Function RemoveGroupsFromUser([string]$username)

{

        $userobj = Get-QADUser -Identity $username

        foreach ($grp in $userobj.memberof)

    		{

                try

                {

                If ($grp.name -eq "adm_Oracle-Hyperion")

			{

            		}

            	else {

            		$null = Remove-QADGroupMember -Identity $grp -Member $username -ErrorAction SilentlyContinue

            		}

                }

                catch

                	{

                        $ErrorMessage = $_.Exception.Message

                        $groupname = $grp.name

                        logmessage -user $username -message "Failed to remove user from Group: $groupname"

                        Write-Output "Failed to remove $username from $grpname"

                	}

            }

}

Any suggestions how I can get this to work?

Creating Multiple columns on csv export using *,@{Name='';Expression={}}

$
0
0

Hi all

Me again!

Is it possible for me to use '*,@{Name='Status';Expression={}}' to create multiple columns as a 1 line of code?

Basically I would like to add 2 columns to my CSV export which is "success" and "Error Exception". I have managed to create 1 column but struggling to add another

I have tried different ones like

$row|Select*,@{Name='Status';Expression={$Failed}},{Name='Status';Expression={$Failed}}|export-csvC:\ps\results.csv-NoTypeInformation-append}

My code so far

try {

        if (Get-ChildItem C:\ps\results.csv -ErrorAction Stop) {

                Write-host -ForegroundColor Red "A Previous Results.csv File has been Found. Delete? Type YES to Continue"}

                $Answer = Read-Host "Type YES to continue"
                if ($Answer -eq 'yes')

                {remove-item C:\ps\results.csv}

}catch{

                Write-host -foregroundcolor green "No Previous File Found"

}finally{}


$csv = import-csv C:\ps\Validation.csv


        ForEach ($row in $csv){

            try{

                Set-Adgroup -Identity $row.groupname -description $row.description -ManagedBy $row.Managedby -ErrorAction Stop


                Write-host -ForegroundColor Green "Group"$row.groupname"was updated Successfully"
                $success = "Success"
                $row | Select *,@{Name='Status';Expression={$Success}} | export-csv C:\ps\results.csv -NoTypeInformation -append



            }Catch{


                Write-host -ForegroundColor red "Group"$row.groupname"Failed to Update. Check the name and try again!"
                $Failed = "Failed"
                $ErrorCode = $error[0].exception
                $row | Select *,@{Name='Status';Expression={$Failed}} | export-csv C:\ps\results.csv -NoTypeInformation -append}


           Finally{}

           }




Problems with icacls and auditing

$
0
0

I have a script that resets all permissions on a set of folders and then applies custom permissions. I have another one that set's up auditing on selected folders. For some reason when I run the script that set's up auditing after running the script setting up permissions the permissions on audited folders are set back to default.
To audit I run
$user = "Everyone"
$rules = "Delete,CreateFiles,AppendData"
$Inheritance = "ContainerInherit,ObjectInherit"
$type = "Success"
$ACL = New-Object System.Security.AccessControl.DirectorySecurity
$rule = New-Object System.Security.AccessControl.FileSystemAuditRule($user,$rules,$inheritance,"None",$type)
$acl.AddAuditRule($rule)
foreach($folder in $folders){ $ACL | Set-Acl $folder}
auditpol /set /subcategory:"File Share" /success:enable
in the script for permissions I have
takeown /F c:\test /A /R /D Y
icacls c:\test /reset /t /c
icacls c:\test /grant:r "NT Authority\Authenticated Users":(CI) (OI) R
icacls c:\test\item1 /inheritance:r /grant:r "admin group": (CI) (OI) RWD /grant:r "read group": (CI) (OI) R /grant:r "builtin\Administrators": (OI) (CI) F  .....
and more lines in pretty much the same manner for diferent subfolders.
Can someone spot where it goes wrong?


yaro

how to connect to a remote computer without credentials !!

$
0
0

i am already done from writing a Powershell script to get some info from other computers in a domain .
it looks somehow weird, but is it possible to run this script test.ps1 on the remote machine without entering the (Credential)
cause it seems to be illogical to run : 

enable-psremoting -Force 

on every machine , then : 

Invoke-Command -FilePath C:\path\test.ps1 -ComputerName computername -Credential domain\usrname


I look forward to your answers

Powershell -ExecutionPolicy ByPass in script

$
0
0

Hi,

I have a powershell script and I don't want to change the ExecutionPolicy on my machine. When I run PS command line and type the following command:

 powershell -ExecutionPolicy ByPass -File test.ps1
the script will run but I dont know how to add this command into my powershell script because I want to run it from context(linke in image) menu when I right click on this powershell script.



How to stop getting prompted to "Confirm"

$
0
0

Hello,

I have some Windows Server 2008 systems that I'm trying to run a powershell script on to delete some temp files, but I keep getting prompted with "Confirm... Y [Yes] [A] Yes to All...... ect"  Is there a way to bypass the Confirm?

Thanks,

Tom


Tom Martin Email: tmartin@caa.com

the output from this script is too wide for the screen and I can't figure out how to apply .Substring() to it to suppress part of the path

$
0
0

I've written a script to find all the files containing a given string, but the output is so wide that posh truncates it and I'm losing the most valuable portion off the right-hand side.  I'm trying to figure out how to apply .Substring() to it to suppress the base path.  Here's the script:

$myString="tblPersPeopleInfo"

# this version gives me the full path, which can result in a lengthy, truncated string

# look for the string in my was1Reports project

$mySsdtPath ="\\servername\users\Christian.Bahnsen\My Documents\Visual Studio 2008\Projects\was1Reports\"

ls $mySsdtPath-Recurse|Select-String$myString|Select-UniquePath

Again, I want to take the output on the last line and apply .Substring(95) (the length of the path stored in $mySsdtPath) to it so that I'll just get the remainder of the path. 

Thanks for any assistance

Christian Bahnsen


ADFS 2.0 No PowerShell SnapIn

$
0
0

Hello,

I installed the ADFS 2.0 server on a Windows 2008 R2 Enterprise server, and did all the updates. When I try to use the PowerShell SnapIn to do some commands I have this error :

PS> Add-PSSnapin Microsoft.Adfs.PowerShell

Add-PSSnapin : No snap-ins have been registered for Windows PowerShell version 2.0

At line:1 char:12

...

I installed and reinstalled ADFS 2.0 a lot of times, tried to follow a lot of work-around (e.g : Paresh's blog, doesn't work at the moment) and I have still the same problem. Maybe I forgot an important thing to do ?

When I type :

PS > get-module -listavailable

The ADFS module is not listed. Do you know how can I install these Adfs PowerShell modules ?

Thank you.

Manage domain via gateway

$
0
0

I have a domain that is on an isolated network.  The only way to manage this domain is via a single server that is part of this domain and has a 2nd NIC in a "management network".  Currently we login to this dual-homed server via the management NIC then can access domain resources.

My goal is to have another workstation on the management network only and manage the domain via Powershell.  The workstation on the management network only has access to the dual-homed server.  The dual-homed server is not a domain controller. How can I use the AD commands exported by the ActiveDirectory module from the management workstation to manage the isolated domain?

I have tried to Enter-PSSession into the dual-homed machine and import-module ActiveDirectory but I get an error.  How can I remotely manage this domain?  Is there some kind of "gateway" I can implement on this on the dual-homed machine that the management workstation can access to manage the domain?


Installing Fonts With Powershell

$
0
0

Hello,


I'm trying to install a bunch of fonts using vb or powershell. I understand that it's not enough to just copy the fonts to C:\windows\fonts these days. I've been having problems using the shell.application object though. If I run:

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace("C:\fonts")
Set objFolderItem = objFolder.ParseName("sbd_____.pfm")

Nothing happens, with either otf,ttf or .pfm fonts. The fonts are copied to the fonts folder but don't show up in apps or in the registry.

The fonts only install if I add : objFolderItem.InvokeVerb("Install")

Is this line literally doign the same thing as i do if I manually install the font when right clicking the file?

My powershell script looks like :

$FONTS = 0x14
$objShell = New-Object -ComObject Shell.Application
$objFolder = $objShell.Namespace($FONTS)
$objFolder.CopyHere("C:\fonts\vagroundedstd-thin.otf")

Can I add the command objFolderItem.InvokeVerb("Install")? Or is there another install command for powershell?

extract powershell commandline arguments from C#

$
0
0

Hello there,

I have a list of powershell commandline executions from windows log events such as this:

powershell.exe -Command "scrip instructions.."-Mta -NoExit .....

I have a script that via regex extracts each pair of arguments for each script:

  • Command = "stuf..."
  • Mta = True
  • NoExit = True

It then applies some machine learning to find odd powershell executions.

Now I have realized that there are several different ways to provide those arguments like with or without quotes, shortened vs unshortened so my regex are starting to fail and picking up spurious data.

I am wondering if there is a class in the Language Automation namespace that does the argument extraction before passing it in the powershell pipeline that I can re-use for my use case.

Let me know !

Issue with erroraction using AD cmdlets

$
0
0

Is it me or do the AD cmdlets behave differently than other cmdlets in terms of erroraction?

I have a simple script that does:

Try
{
$costcenter = get-aduser $ad_user -properties * | select -Expandproperty CostCenter
}

Catch
{
write-host "It failed knucklehead"
}

For some reason that is not fixable for the purposes of this thread/question, sometimes running get-aduser for an AD user throws an error about year, month, day parameters or something.  I can NOT find a way to suppress that error and move on.  I have put $erroractionpreferance = "silentlycontinue" above this command, I have put -Erroraction silentlycontinue at the end of the command.  I have done both.  No matter what, it always throws an exception and jumps to the catch block.  The reason this is important is because sometimes users don't have a cost center, so I am running a Do Until loop until $costcenter has a value.  If there is no value after checking a user, I will check for their manager and keep going up the chain until I get a costcenter.  When aduser throws an error, all of this logic is completely hosed.

What am I doing wrong?

 


Report for Folder Access lists

$
0
0

Hi Guys,

I need to generate the report for Non-Inherited access rights list for the sub directories with User SID, Account Name, and Group Name(AD Group Name - users will be added in to the Group). I had written below Script to fetch the details. In that i would like to include Directory path as well. Please help me to get the details and complete the script.

I used NTFS Security Module to fetch the ACL details

Expected Output:

SID  AccountName  GroupName  Path

Script:

                        

Import-Module ".\NTFSSecurity.psd1

$RootFolders = Get-ChildItem -Path "D:\Data" -Directory

foreach($RootFolder In $RootFolders){

$NonInheritedAccessADGroupNameTemp = "AD-FS-NonITest"

$FolderRootPath = $RootFolder.FullName

Get-ChildItem2 -Path $FolderRootPath -Recurse -ErrorAction Stop | ForEach-Object {

        $AllAccess = Get-NTFSAccess -Path $_.FullName

$NonInheritedAccess = $AllAccess | Where-Object { $_.IsInherited -eq $false }

if ($NonInheritedAccess -ne $null -OR $AllAccess -eq $null) {
                $NonInheritedAccess | Where-Object { $_.AccessControlType -eq 'Allow' } | select -ExpandProperty Account | select SID, AccountName, @{N='GroupName';e={ $NonInheritedAccessADGroupNameTemp  }} | Export-Csv -Path ".\report.csv" -Delimiter ';' -Encoding UTF8 -Append -NoTypeInformation

             }
}

}

Thanks in Advance.

Deepika E

Removing a user (child domain) fron an AD Group (Parent domain)

$
0
0

I am trying to write a powershell script to remove a user (who is in child domain) from an AD group that's in parent domain.

I tried various script to remove the user but I just get different errors. 

Remove-ADGroupMember-Identity $group -Members jdoe -confirm: $falseError message:Cannot find and object with identity:"jdoe" under: DC: corp, DC:hello, DC=com

so, I did

$user =Get-Aduser-Filter{SamAccountName-eq "jdoe"}-Server child.corp.hello.comRemove-ADGroupMember-Identity $group -Members $user -confirm: $falseError message:The specified account name is not a member of the group

hen, I did

Remove-ADGroupMember-Identity $group -Members $user.DistinguishedName-confirm: $falseErrorMessage: A referral was returned from the server.

two domains are parent and child which means they are in the same tree.

Please help, thank you

Viewing all 21975 articles
Browse latest View live


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