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

Returning employeeID property with System.DirectoryServices.DirectorySearcher

$
0
0

Due to some constraints as to where the script will be used, I'm using the ADSI method to dump out a user report. It needs to include the employeeID.

$filter = "(objectCategory=User)"
$ou = New-Object System.DirectoryServices.DirectoryEntry("LDAP://OU=Domain Users,DC=example,DC=pri")
$Search = New-Object System.DirectoryServices.DirectorySearcher
$Search.SearchRoot = $ou
$Search.PageSize = 1000
$Search.Filter = $Filter
$Search.SearchScope = "OneLevel"
$Props = "name","employeeID"
foreach ($i in $Props){$Search.PropertiesToLoad.Add($i)}
$Search.FindAll()  |  foreach {
    $_.properties.name
    $_.properties.employeeID
}

All this does is return the account name. And yes, there are accounts that should be returned by this search that contain an employeeID. If I set strictmode, I get the error "The property 'employeeID' cannot be found on this object. Verify that the property exists."

It won't find a custom attribute we have set on the user objects either.

If I do a straight ADSI query, they're there with no problems. I thought System.DirectoryServices.DirectorySearcher could return any LDAP attribute.

$user = [ADSI]"LDAP://CN=EXAMPLE,OU=Domain Users,DC=example,DC=pri"
$user.employeeID
020419

Is it some problem with the PropertiesToLoad in the searcher? They look ok to me.

$search.PropertiesToLoad
name
employeeID
ADsPath

PowerShell - Set Zone Transfers on Secondary DNS Zones

$
0
0

I've a few hundred zones that I need to update the zone transfers on, a mix of primary and secondary zones.

I can find a way to update the primary zones with the below:

[CmdletBinding()]
Param(
  [string]$ZoneName
)

if(-not($ZoneName)) {$ZoneName = Read-Host -Prompt "You must provide a Zone Name - e.g. whatever.com"}


Set-DNSServerPrimaryZone -ComputerName "DNSSERVERNAME" -Name $ZoneName -SecondaryServers "1.2.3.4","5.6.7.8" -SecureSecondaries TransferToSecureServers 

Logically I thought I could use "Set-DNSServerSecondaryZone" to do something similar with my secondary zones - but alas there's nothing in there to define the SecondaryServers or seemingly anything on the zone transfers at all...

Does anyone have any tips or tricks I can use to amend these?   Currently I'd like to try and encompass it all in PS scripts for easy, but outside PowerShell my only thought is to drop back to dnscmd - e.g.

dnscmd DNSSERVERNAME/zoneresetsecondaries SECONDARYZONENAME /securelist 1.2.3.4 5.6.7.8

Thanks in advance



Invoke-WebRequest property, analog of "LocationURL" one of "InternetExplorer.Application" ComObject

$
0
0

Is there Invoke-WebRequest property, analog of "LocationURL" one of "InternetExplorer.Application" ComObject?

Example: 

$ie = new-object -ComObject "InternetExplorer.Application"

#some code...

$token=$ie.LocationURL.tostring()

I need to get token from address bar for this service https://oauth.vk.com/authorize?client_id=1&display=page&redirect_uri=https://oauth.vk.com/blank.html&scope=friends&response_type=token&v=5.8

like here

https://oauth.vk.com/blank.html#access_token=57afnb9797f2d1ef3f5cd6248094ce0c4acc6dd2a778210ab8c2b53cbf13ee38cafb0afb2b7c576db9fca&expires_in=86400&user_id=1

Powershell Notification of users about the expiration of the certificate

$
0
0

It is required to notify the user about the expiration of his personal certificates. I found the user's logs and his certificate.

 # I define the user login

     $user = $env:Username 


 # By login I recognize the name that is buried in the DisplayName field

    $ADdate = GET-ADUser -Identity $user -Properies DisplayName 

    $FullName = $ADdate.DisplayName

 # A variable that stores in itself how many days left before the expiration of the certificate

     $Threshold =30

 # A variable that stores the date to which certificates are checked

    $DeadLine = (Get-date).AddDays($Threshold)


 # Search for personal certificates corresponding to the condition and calculate how many days are left before the certificate expires

    $cert = dir Cert:\CurrentUser\my | foreach {if($_.NotAfter -le $deadline -and $_.Subject -notlike $FullName) {$_.| select issuer, subject, notafter, @{label="expires in(days)";Expression={($_.NotAfter - (Get-Date)).days}}}}


 On an output I receive:

    Issuer CN=Issuing  CA, O=BANK, L=Moscow, DC=URAL, DC=BANK, DC=LOC, C=RU 

    ----------

    Subject CN=Ivanov Ivan Ivanovich, OU=Users, OU=OOO BANK, DC=URAL, DC=BANK, DC=LOC

    ----------

    NotAfter 02.08.2020 8:58:19 

    ----------

    expires in (days)       725


in the personal are buried many certificates, it is necessary to choose Ivanov Ivan Ivanovich and bring him a message about the end of the validity of his certificate !!! and it can be not one or two!
I do not understand how this can lead to a state:

    Dear Ivanov Ivan Ivanovich, the validity of the certificate Issuing CA ends on 08/02/2020 8:58:19 in 725 days

                             

Returning ANY property with System.DirectoryServices.DirectorySearcher & whenchanged

$
0
0

OK, so there is this old thread - https://social.technet.microsoft.com/Forums/windowsserver/en-US/15666ba3-ba83-4ceb-9af6-77194072b413/returning-employeeid-property-with-systemdirectoryservicesdirectorysearcher

which had a nice answer, but I would need to have the property returned only when using whenchanged

$todaystamp = Get-Date -UFormat %Y%m%d%H%M%S.0Z;

whenchanged>=$todaystamp

Any idea how?

Seb


Login button click script not working in IE

$
0
0

Hello there

The script is not throwing any errors but i am unable to automate login to website(Its automatically entering my username and password though but not clicking the Login button)

HTML code

<button type="submit" class="btn btn-primary pull-right form-control">Login</button>

Powershell script

$ie = New-Object -com internetexplorer.application

$Url = "http://URL"

$ie.visible = $true

$ie.navigate($Url)

While ($ie.Busy -eq $true) {Start-Sleep -Seconds 3;}

$usernamefield = $ie.document.getElementByID("domainUsername")
$usernamefield.value = 'mbijja'

$passwordfield = $ie.document.getElementById("secret")
$passwordfield.value = 'pass*'

$Link=$ie.Document.getElementsByTagName("button") | where-object {$_.type -eq 'submit'}
$Link.click();

This URL has API tokens-fyi

Thanks

mbijja

how to include streamwriter

$
0
0

  I've been searching on how to include streamwriter since this file I'm do a replace in is large and want to as fast as
possible create the new output file.

$Start = Get-Date
#
# Start
#

$LogFilePath = "C:\compress_in\usermstr.csv"
$FileStream = New-Object -TypeName IO.FileStream -ArgumentList ($LogFilePath), ([System.IO.FileMode]::Open), ([System.IO.FileAccess]::Read), ([System.IO.FileShare]::ReadWrite);
$ReadLogFile = New-Object -TypeName System.IO.StreamReader -ArgumentList ($FileStream, [System.Text.Encoding]::ASCII, $true);
[int]$LineNumber = 0;

 
# Read Lines
while (!$ReadLogFile.EndOfStream)
{
	$LogContent = $ReadLogFile.ReadLine()
	$LineNumber++    
    $data = $LogContent.Replace('"','')

        
	}
$LineNumber
$ReadLogFile.Close()
$End = Get-Date
# Show the result
New-Timespan -Start $Start -End $End
 I want to create a new output file with the quote marks removed.

 Thanks.

How to remove an Azure Account from Powershell and Login with a new account

$
0
0

I am using the command Remove-Azureaccount to remove a current existing account attached to a particular subscription and I would like to login with a new account to see some other subscription.

Both the subscriptions are in Resource Manager Mode.

What is the current command to remove an account or delete a subscription  in Resource Manager Mode, "Remove-Azureaccount" is not working and throwing me error

Remove-AzureAccount : User name is not valid.
Parameter name: accountId
At line:1 char:1
+ Remove-AzureAccount -Name "infy_107797@outlook.com"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Remove-AzureAccount], ArgumentException
    + FullyQualifiedErrorId : Microsoft.WindowsAzure.Commands.Profile.RemoveAzureAccountCommand
 


Pallab Chakraborty


New-ADUser Script Help

$
0
0

I want to create a portion of the script that checks if the samAccountNameexists based on the givenName and surName that is entered at the beginning of the script. If it does, I'd like to have the script create thesamAccountName based on the first two letters of the first name then the full last name. 

For example:

$GivenName = "John"

$SurName = "Test"

$SamAccountName = "$($GivenName.Substring(0,1))$Surname"

Returns: Jtest

I'd like the samAccountName to be:
Jotest if the samAccountName of Jtest exists already. 

Powershell OCR

$
0
0

I would like to be able to script OCR against a jpg.

I have tried installing MODI from office 2007 / 2010, but had no luck.

I read that Windows now has OCR available for UWP applications. is this in any way available via PowerShell?

I know there are internet web pages available, but I would prefer to keep processing local.

Thanks!

Tom

Third Firday of the month

$
0
0
I need to reboot a few servers on the 3rd Friday of the month but I'm struggling with the PowerShell commands. Anyone able to assist?

stop the script when var ProfitThresholdToStopScript = 50 how can i solve this

$
0
0
   var config = {};
// ------------------------------------------------------------------------------------------------------------------------
var BaseBet = 40;           // Set the base bet here.
// ------------------------------------------------------------------------------------------------------------------------
var BaseCashout = 1.50;     // Set the base cashout here
// ------------------------------------------------------------------------------------------------------------------------
var Skips = {
    values: [0],        // Set skips here, put -1 for reset, put -2 for stop
    currentIndex: 0,
    getValue: function() {
        if (this.currentIndex == this.values.length ) {
            this.currentIndex = 0;
        }
        return this.values[this.currentIndex++];
    }
};
// ------------------------------------------------------------------------------------------------------------------------
var RecoveryCashouts = [15, 1.6, 1.1, 1.05, 1.2, 2, 2, 2];  // Set the recovery cashouts here
var RecoveryBets     = [5, 6, 1, 1, 2, 1, 1, 1];            // Set the bets to do after a loss here
// ------------------------------------------------------------------------------------------------------------------------
var SoftRecovery = 0;   // Set this to zero for lower risk, set to one for lucky recovery...
// ------------------------------------------------------------------------------------------------------------------------
var LuckyRecovery = 0;  // Set this to one if you feel especially lucky...
// ------------------------------------------------------------------------------------------------------------------------
var StopScriptOnContinuousLoss = 1; // Set this to one to stop instead of reset
// ------------------------------------------------------------------------------------------------------------------------
var ProfitThresholdToStopScript = 50;
// ------------------------------------------------------------------------------------------------------------------------
var TestMode = {
    active: true,
    lastGame: {
        wager: false,
        cashout: undefined,
        reset: function() {
            this.wager = false;
            this.cashout = undefined;
        }  
    }
};
// ------------------------------------------------------------------------------------------------------------------------
var SuperRecovery = {
    occurrence: [1, 0, 0, 0, 0, 0, 2, 4, 5, 3, 3, 2],
    threshold: [20, 0, 0, 0, 0, 0, 19, 21, 20, 32, 25, 28],
    currentIndex: 0,
    occurrenceCounter: 0,
    isPassed: function () {
       var lastGame = engine.history.first();
       var curOccurr = this.occurrence[this.currentIndex];
       var curTresh = this.threshold[this.currentIndex];
       var returnValue = false;
       //log ("curOccurr = ", curOccurr, " curTresh = ", curTresh);
       if (curOccurr  == 0 && curTresh == 0) {
          this.occurrenceCounter = 0;
       } else if (curOccurr > 0 && lastGame.bust <= curTresh) {
          this.occurrenceCounter++;
       } else if (curOccurr < 0 && lastGame.bust >= curTresh) {
          this.occurrenceCounter++;
       } else {
          this.occurrenceCounter=0;
       }
       if (this.occurrenceCounter== Math.abs(curOccurr)) {
          if (curOccurr == 0 && curTresh == 0) {
             log('skipping the array elements');
          } else if (curOccurr >= 0) {
             log('val is less than ', curTresh ,' continuously in ',curOccurr,' running times', lastGame.bust ,'x');
          } else if (curOccurr <= 0) {
             log('val is greater than ', curTresh ,' continuously in ',Math.abs(curOccurr),' running times', lastGame.bust ,'x');
          }
          returnValue = true;
          this.occurrenceCounter = 0;
          this.currentIndex++;
       }
       log('Game crashed at ', lastGame.bust ,'x');
       if (this.currentIndex == this.occurrence.length - 1) {
          this.currentIndex = 0;
       }
       return returnValue;
    }
};
// ------------------------------------------------------------------------------------------------------------------------
function MasterConditionPassed() { //return true to pass master condition
    //for the sake of example:
    //var games = engine.history.toArray();
    //if (games[0].bust < 5 && games[1].bust < 5 && games[2].bust < 5) {
    //   log("Below 5 3 or more times!")
    //   return true;
    //} else {
    return false;
    //}
}
// ------------------------------------------------------------------------------------------------------------------------
function GetLastGame() {
    var lastGame = engine.history.first();
    if (TestMode.active) {
        lastGame.wager = TestMode.lastGame.wager;
        if (TestMode.lastGame.cashout < lastGame.bust) {
            lastGame.cashedAt = TestMode.lastGame.cashout;
        }
    }
    return lastGame;
}
// ------------------------------------------------------------------------------------------------------------------------
function DoRecoveryMode() {
    log('Bet so far this loss streak: ' + BetSoFar);
    //var RecoverBet = Math.ceil((Math.pow(Math.ceil(100 / ((RecoveryCashouts[gameState-1] * 100) - 100)), gameState) * BetSoFar));
    var RecoverBet = RecoveryBets[gameState - 1];
    if (LuckyRecovery != 0) {
        RecoverBet += (LuckyRecovery * gameState);
    }
   
    PlaceBet(RecoverBet, RecoveryCashouts[gameState-1]);
}
// ------------------------------------------------------------------------------------------------------------------------
function PlaceBet(bits, cashout) {
    log('Betting ' + bits + ' for cashout ' + cashout + 'x');
    BetSoFar += bits;
    if (!TestMode.active) {
        engine.bet(bits * 100, cashout);
    }
    TestMode.lastGame.wager = true;
    TestMode.lastGame.cashout = cashout;
    log(' ');
}
// ------------------------------------------------------------------------------------------------------------------------
 
var startBalance = userInfo.balance / 100;
log('Starting script with balance ' + startBalance);
var gameState = 0;
var gamesToSkip = 0;
var BetSoFar = 0;
var games = 1;
 
engine.on('GAME_STARTING', function()  {
    if (MasterConditionPassed()) {
        stop("Stop due to master condition")
    }
    if((games % 10) == 0) {
        var sessionResult = Math.ceil(((userInfo.balance / 100) - startBalance) * 100) / 100;
        log('Current session result: ', sessionResult, ' bits');
        if (sessionResult >= ProfitThresholdToStopScript) {
            gameState = -2;
        }
    }
 
    switch(gameState) {
        case -2:
            stop("Stopped");
            break;
        case -1:
            gameState = 0;
            BetSoFar = SoftRecovery;
            break;
        case 0:
            PlaceBet(BaseBet, BaseCashout);
            break;
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 6:
        case 7:
        case 8:
            if (Skips.getValue() == -1) {
                gameState = -1;
                return;
            }
 
            if (Skips.getValue() == -2) {
                gameState = -2;
                return;
            }
           
            if (gamesToSkip <= 0) {
                if (SuperRecovery.isPassed()) {
                    DoRecoveryMode();
                }
            } else {
                gamesToSkip--;
                if (gamesToSkip === 0) {
                    log('Recovery after this game !');
                }
                else {
                    log('Skipping ' + gamesToSkip + ' more games...');
                }
            }
            break;
        default:
            gameState = -1;
            break;
    }
    games++;
});
 
 
engine.on('GAME_ENDED', function() {
    var lastGame = GetLastGame();
    if (!lastGame.wager) {
        return;
    }
   
    if (lastGame.cashedAt) {
        if(gameState == 0) {
            log('Won!');
        } else {
            log('Recovered from ' + gameState + ' deep loss streak!');
        }
        gameState = 0;
        BetSoFar = SoftRecovery;
    } else {
        gameState++;
        gamesToSkip = Skips.getValue();
        if(gamesToSkip > 0) {
            log('Lost! Waiting ' + gamesToSkip + ' games...');
        } else {
            log('Lost hard! Skipping one game and resetting...');
        }
    }
    TestMode.lastGame.reset();
});

Change Job Titles in AD via Powershell

$
0
0

Hi

I am running the following script in an attempt to update over 500 user job titles within Active Directory:

Import-CSV -Path C:\Users.CSV | Foreach-Object {
#properties from the csv
    $mail  = $_.email
    $title = $_.jobtitle
    Get-ADUser -Filter {(mail -eq "$mail")} | Set-ADUser -Title $title

The CSV file format is as below:

email,title

test.user,Test user 1

test.user2,Test user 2

The script runs without error but does not perform any change to the user profile

any assistance would be greatly appreciated


Powershell Skype Online Session does not work.

$
0
0


I try to use Skype Online Session but it does not work. Any ideas what to do? I have tcp/443 connection on a place. And credentials are working fine.

Powershell Scheduled Task; Encrypted Password: Key not valid for use in specified state

$
0
0

Hello everyone!

This is my first post in this forum and I'm looking forward to it!

Anyway here's the problem. I got a Powershell Script which I want to implement in the Task Scheduler. The script automates the VMWare Tool upgrade. The problem is the following: when I manually run the task over Powershell it completes without an error. BUT if I run the task through Task Scheduler it displays an error in the log I create.

Here's the script:

Start-Transcript -Path C:\temp\log.txt -Append

#Decrypt Password
$securePass = Get-Content C:\Path\EncryptedPwd.txt | ConvertTo-SecureString
$BSTR = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($securePass)
$Pwd = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)

#Username
$user = "USER"


#Load VMware Power-CLI Snap-In
Get-Module -Name VMWare* -Listavailable | Import-Module
#vCenter FQDN
$VCenterName = "VCenterFQDN"
#Connect vCenter 
Connect-VIServer -Server $VCenterName -User $user -Password $Pwd 
#Update VMware Tool nach TAGS
Get-VM -Tag "Tag" | Where-Object { $_.ExtensionData.Guest.ToolsVersionStatus -eq 'guestToolsNeedUpgrade' -and $_.PowerState -eq 'PoweredOn' } | Get-VMGuest | Where-Object { $_.GuestFamily -eq "windowsGuest" } | Update-Tools -NoReboot –RunAsync

Stop-Transcript

#exit(0)


<##
#Pausieren des Scripts 
Start-Sleep -s 180
#Generate Report für PRTG-Check 
Get-VM -Tag "Tag" | Where-Object { $_.ExtensionData.Guest.ToolsVersionStatus -eq 'guestToolsNeedUpgrade' -and $_.PowerState -eq 'PoweredOn' } | Get-VMGuest | Where-Object { $_.GuestFamily -eq "windowsGuest" } | Out-File C:\PathToReport.txt -width 120
##>

The error in the log is the following:

At C:\PathToPSScript.ps1:13 char:70
+ ... ent C:\Path\EncryptedPwd.txt | ConvertTo-SecureString
+                                                    ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [ConvertTo-SecureString], CryptographicException
    + FullyQualifiedErrorId :
ImportSecureString_InvalidArgument_CryptographicError,Microsoft.PowerShell.Commands.ConvertToSecureStringCommand
ConvertTo-SecureString : Key not valid for use in specified state.

As you can see there's a problem in the ConvertTo-SecureString and I have not found a possible explanation till now why it is working when I start the script manually and why it isn't working when it is run throught the Task Scheduler.
There are more errors, but they are errors due to the ConvertTo-SecureString error.

Can anyone help me here?




get all places of URL usage

$
0
0

Hello guys,

is there a way to find out all the places where a specific URL is used by using PowerShell ?

I tried it this way:

Add-PSSnapin "Microsoft.SharePoint.PowerShell"

get-spsite -limit all| Where-Object {$_.Url -like "https//AAA.BBB.com/CCC"}

Thank you in advance.

a lot of cmdlets missing from powershell

$
0
0

The o/s is windows 2012 R2. When I am trying to manage some of the tasks about Active Directory such as bulk user password and bulk user import, a lot of cmdlets are missing. I did type "import-module ActiveDirectory". What have I missed? I am not manage azure Active Directory though.

Please advise! Thank you very much!

Sidhistory

$
0
0

Hi,

For migration project, need to see how many users were migrated. Is there a script for pulling sidhostory for all users from a  text file or an OU? 

Using an environment variable with a "."

$
0
0

An environment variable exists on all our machines that has a period in it, as in "abc.xyz".

PowerShell chokes on $Env:abc.xyz.

PS C:\Windows\system32> ? $Env:abc.xyz
Where-Object : Cannot bind argument to parameter 'FilterScript' because it is null.
At line:1 char:3+ ? $Env:abc.xyz+   ~~~~~~~~~~~~+ CategoryInfo          : InvalidData: (:) [Where-Object], ParameterBindingValidationException+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.WhereObjectCommand

I've tried a back apostrophe to escape the period but that doesn't seem to work.

What's the PS equivalent for %abc.xyz%?

TIA

New-PSDrive error with double hop

$
0
0

I'm trying to install software from a UNC share path, executing a script from serverA, to install the software on serverB.  The install executables will be called over a UNC share on serverC - your classic double hop issue.

While the installation process does complete successfully, and New-PSDrive "does something", it is still throwing an exception even if redirected to NULL:

A specified logon session does not exist. It may already have been terminated
    + CategoryInfo          : InvalidOperation: (Share:PSDriveInfo) [New-PSDrive], Win32Exception
    + FullyQualifiedErrorId : CouldNotMapNetworkDrive,Microsoft.PowerShell.Commands.NewPSDriveCommand

System.ComponentModel.Win32Exception (0x80004005): A specified logon session does not exist. It may already have been terminated

New-PSDrive is granting me access to the share from serverB to serverC.  In the block below you can see the difference when you comment out the New-PSDrive statement - GCI (and my install) will either succeed or fail.

Which part of the New-PSDrive command is failing?  It seems it's trying to do 2 things - one which succeeds and grants my session access to the share  - and the other is trying to create the mapping which fails.  Note that Get-PSDrive does not show a record for the share on serverC even though it becomes accessible over UNC path.

### Execute from serverA

$Share_Root = '\\serverC\share' $CRED = Get-Credential ($env:USERDOMAIN + '\' + $env:USERNAME) Invoke-Command -ComputerName 'serverB' -Credential $CRED { Try {New-PSDrive -Root $using:Share_Root -PSProvider FileSystem -credential $using:cred -Name 'Share' -ErrorAction Stop} Catch {Write-Host $_.exception} $ShareFile = "$using:Share_Root\readme.txt" Get-ChildItem $ShareFile }


Viewing all 21975 articles
Browse latest View live


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