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

how to change powershell languagemode to FullLanguage

$
0
0

Hi,

on my windows 10 machine powershell script execution started failing with below error :

 Cannot dot-source this command because it was defined in a different language
  mode. To invoke this command without importing its contents, omit the '.' operator.

I check my language mode and it was : ConstrainedLanguage

I tried to set environment variable __PSLockdownPolicy to 0 and 

$ExecutionContext.SessionState.LanguageMode=[System.Management.Automation.PSLanguageMode]::FullLanguage

but no luck at all.

Can you guys help me how to change language mode or any other pointer in microsoft's powershell team to contact.


Powershell - Excel - Output all the values matching the string

$
0
0

Hello Experts,

I am looking for a PowerShell script that will go through an excel file.

If the date's column has today's date, the script needs to output the adjacent value of the matching string. (left side cell)

I have partially succeeded in this. However, the script is just returning the very first value and not all the values across the file.

I need to have some kind of loop setup in the script so that the script outputs all corresponding values matching the string. Not just very first value. Could you

$File = "C:\temp\cert.xlsx"
$today = (get-date).ToString("d/MM/yyyy")

$Excel = New-Object -ComObject Excel.Application
$Excel.visible = $true
$Workbook = $Excel.workbooks.open($File)
$Worksheets = $Workbooks.worksheets
$Worksheet = $Workbook.Worksheets.Item(2)

$SearchString = $today

$Range = $Worksheet.Range("B1").EntireColumn


$Search = $Range.find($SearchString)

 $target = $Search.offset(0,-1)
 $target.text
 

please advise. Thank you.

Replacing generated Image file instead of creating a new one at every run

$
0
0

HI,

We found this code at this location. https://github.com/octan3/img-clipboard-dump. We are beginner in Powershell and we are having a difficult time trying to understand the code.

Add-Type -Assembly PresentationCore
$img = [Windows.Clipboard]::GetImage()
if ($img -eq $null) {
    Write-Host "Clipboard contains no image."
    Exit
}

$file = "{0}\clipboard-{1}.jpg" -f [Environment]::GetFolderPath('MyPictures'),((Get-Date -f s) -replace '[-T:]','')
Write-Host ("`n Found picture. {0}x{1} pixel. Saving to {2}`n" -f $img.PixelWidth, $img.PixelHeight, $file)

$stream = [IO.File]::Open($file, "OpenOrCreate")
$encoder = New-Object Windows.Media.Imaging.JpegBitmapEncoder
$encoder.QualityLevel = 90
$encoder.Frames.Add([Windows.Media.Imaging.BitmapFrame]::Create($img))
$encoder.Save($stream)
$stream.Dispose()& explorer.exe /select,$file

We would need to get this modified so that the files gets overwritten at every run instead of creating a new one at each run. How can we edit the script so that it would save to a specific folder with a file name provided that the path and the file name has been hard-coded inside the script. Please assist. 

For example : Say, we need the file to be saved into this path : --> C:\Images and the filename should be --> Image01.jpg resulting in this --> C:\Images\Image01.jpg

Permission denied only when PSRemoting

$
0
0

Hi,

I want to run a command remotely but when I do it, it gives me a permission denied.

Invoke-Command -Credential (Get-Credential) -ComputerName srvdfs02 -ScriptBlock { Get-DfsnFolder -Path "\\pierre.be\homes\xxxxxx"}

The credential used is domain admin and have full right on all. When I run the Get-DfsnFolder command directly on the server, it works well. But, if I do a PSSession, enter into it and run the command it gives me the same error than the invoke-command.

So,

Directly -> OK

By Enter-pssession -> Fail

By Invoke -> Fail

Have you got any idea ?

Regards,

Arnaud H.

Unable to add DHCP failover peer relation from remote server

$
0
0

Hi 

 I am trying to establish the failover relation ship between two windows servers (w1 and w2 which are 2012 version) with power shell commands like
Add-DhcpServerv4Failover -ComputerName "dhcpserver.contoso.com" -Name "SFO-SIN-Failover" -PartnerServer 10.0.0.99 -ScopeId 10.10.10.0,10.20.20.0 -LoadBalancePercent 70 -MaxClientLeadTime 2:00:00 -AutoStateTransition $True -StateSwitchInterval 2:00:00

but this command will be executed on one of windows server from an external linux machine(external remote), where winrm being the interface between the linux and windows. This winrm will carry the command from linux and gets executed on w1 at that time it is trying to communicate to another windows server w2 to cross check failover already exists or not but it is unable to communicate w2 stack trace gives me permission denied 

<S S="Error">Add-DhcpServerv4Failover : Failed to verify if a failover relationship by the_x000D__x000A_</S>
   <S S="Error">nameSFO-SIN-Failover exists on server 10.0.0.99._x000D__x000A_</S>
   <S S="Error">At line:1 char:74_x000D__x000A_</S>
   <S S="Error">+ if (-not(Get-DhcpServerv4Failover | ? { $_.Name -eq "MSDHCP0037Peer"})){ _x000D__x000A_</S>
   <S S="Error">Add-Dhc ..._x000D__x000A_</S>
   <S S="Error">+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~_x000D__x000A_</S>
   <S S="Error">~~~_x000D__x000A_</S>
   <S S="Error">+ CategoryInfo          : PermissionDenied: (MSDHCP0037Peer:root/Microsoft _x000D__x000A_</S>
   <S S="Error">/...erverv4Failover) [Add-DhcpServerv4Failover], CimException_x000D__x000A_</S>
   <S S="Error">+ FullyQualifiedErrorId : WIN32 5,Add-DhcpServerv4Failover_x000D__x000A_</S>
   <S S="Error">_x000D__x000A_</S>

It says permission denied can i know what are the permissions for the user to establish the failover relation ship, the issue is it is unable to communicate the peer server to cross check when i sent request from linux server (linux-->server1-->server2)  how to add permission to user to perform communication.

Reference:  Posted same issue in the below link

https://social.technet.microsoft.com/Forums/en-US/c3f0dfc3-7875-4993-889d-be91868b939b/unable-to-add-dhcp-failover-peer-relation-from-remote-server?forum=winserveripamdhcpdns

 Thanks                                                                                                                                                      TejaShetty



Script for AD OU permissions

$
0
0

I am trying to right a script, that will allow me to hide/restrict access to OUs to certain security groups.  Essentially I am trying to replace the old Active Roles server's functionality.

Currently I have a script that creates the OUs (and sub OUs), creates the security groups, all fed by form entry.  Once the groups are created, I need to be able to apply restrictions on them to block previously created OUs:

OU1 contains SG 1

OU2 contains SG 2

I need to block SG2 from seeing the contents of OU1 and vice versa.

I have gotten close with a few ACE and ACL scripts but I can't quite get the results I want.  Can anyone help?

Trimming XML output

$
0
0

Hi Everyone

I am stuck with a problem that i haven't been able to solve, so i am asking for your help :)

Long story short, i pull data from our BigFix servers with Powershell. This works.

My code to run the request and save output to XML.

Invoke-WebRequest -Uri $request2 -Credential $login | Select-Object * | Out-File D:\bigfix\bigfix_Output.xml -Width 1000

The Output is a fairly well formated XML file. I then want to trim the XML file and prepare it for further processing.

Example of XML file output:

I want to trim the document and remove all text above the <?xml version="1.0" encoding="UTF-8"?> line.

I have tried to read up on trimming with Powershell, but i haven't been able to solve the problem. Perhaps i could simply edit my Invoke-Webrequest code and justuse Select-Object to select the part i need. But i have not been able to identify an object that returns only the essential XML body.

Can anyone help with an example of trimming all text before <?xml version="1.0" encoding="UTF-8"?> or should i edit my Invoke-Webrequest code?

Any help are more than welcome.

Thanks in advance.

%username conversion to correct SamAccountName.

$
0
0

Dear Community,

I am currently creating a script to ease user creation on Windows Server 2019 ST.

its a very basic script i got from the internet and created my own.

New-ADuser -Name "" -DisplayName "" -HomeDrive "H:" -HomeDirectory "\\Shares\%USERNAME% -GivenName "" -Surname "" -SamAccountName "test" -UserPrincipalName "" -Path "OU=Users,OU=Active Users,DC=Domain,DC=local" -AccountPassword(Read-Host -AsSecureString "Input Password") -Enabled $true

this script works almost 100% the only problem i am facing is that when using the HomeDirectory parameter with the %username% input it does not convert this to the samAccountName automatically. it just inputs it as soon.

with the little language knowledge i have i know everything between "" is seen as a string so it writes it down as seen.

But upon running the script i would like it to recognize it and convert the %username% to test.

Thank you in advanced and will kindly wait for any suggestions.


pass in secure password to SQL connection

$
0
0

 The process runs on a remote(in DMZ SQL box) where I need to pass in a secured password to the process.

  How would the SQL connection look like, and is that the best method?

    Thanks.

# build the file with the encrypted password
ConvertTo-SecureString "xxxx" -AsPlainText -Force | ConvertFrom-SecureString | Out-File "C:\password_test\job_pwd.txt"

Modify User's Logonworkstation with multiple workstation list

$
0
0

Hi Genius Guys

I have CSV file with user names and computer names. given example below

SamAccountName Workstations

User1WKS231

User2WKS453

user3Laptop321

Now I need to get all users given above to add workstations in Logon Workstation list. See below snapshot.

Please help me to achieve it.

I got one script below but that is only for one user.

I need to add one user to one workstation which are in the CSV file.

http://community.spiceworks.com/topic/402067-modify-user-s-logonworkstation-with-multipile-stations-list-powershell

===========

Import-ModuleActiveDirectory$complist=Import-Csv-Path"c:\PCList.csv"|ForEach-Object{$_.NetBIOSName}$UserProperties=Get-AdUser-Identityusername-PropertiesLogonWorkstations$comparray=($UserProperties).LogonWorkstationsforeach($compin$complist){$comparray+=","+$comp}Set-ADUser-Identityusername-LogonWorkstations$comparray

Adding tag in Web.config

$
0
0
Dear All,



In my web.config I want to add the following tags through Windows Powershell Script

this tag should go between <assemblies></assemblies>
<add assembly="System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A" />

This tag should go between <handlers></handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="/v1/*" verb="GET,POST,DELETE" type="System.Web.Handlers.TransferRequestHandler"preCondition="integratedMode,runtimeVersionv4.0" />



I have started to write script but I could only go this far


$webConfig = '.\web.config'
[xml]$web =  (Get-Content $webConfig)


Any help would be greatly appreciated


Powershell - Downloading excel file from Online sharepoint portal

$
0
0

Hi Experts,

 I am having trouble downloading excel file from online sharepoint portal using power shell. Could you please point me to the right directions. Here is the error. Thank you. 

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

Exception calling "DownloadFile" with "2" argument(s): "The remote server returned an error: (403) Forbidden."
+ $WebClient.DownloadFile($SharePoint, $Path)

   + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
   + FullyQualifiedErrorId : WebException
$SharePoint = "https://MyCompanyOnlineSharepointPortal/SomeExcelFile.xlsx"
$Path = "c:\Temp\SomeExcelFile.xlsx"

#User Information'

$username = "Myusername@Company"
$password = "Mypassword"

#Download Files

$WebClient = New-Object System.Net.WebClient
$WebClient.Credentials = New-Object System.Net.Networkcredential($userName, $password)

$WebClient.DownloadFile($SharePoint, $Path)

Wrong path type and size on mounted samba share on Windows 10

$
0
0

Hi,

I have been asked at answers.microsoft.com to ask my question here.

I use a pretty simple python script (also tried a nodejs script) like the one at the end to find all files in a directory and its subdirectories together with their file size and modified time. Therefore the script uses stat syscall to retrieve information about a path: type (regular file, directory etc.), size, modified time.

If I run the script on a local folder on Windows 10, Windows 7 and Ubuntu everything works fine. If I run the script on Windows 7 or Ubuntu on a folder that is a mounted samba share, everything works fine, too.

However, if I run the script on Windows 10 on a folder that is on a mounted samba share, things start to get weird. I get error messages like the following:

C:\Users\Biggie\Scripts>python test.py
Traceback (most recent call last):
  File "test.py", line 10, in <module>
    childs = listdir(next)
WindowsError: [Error 267] The directory name is invalid: 'y:\\some\\path\\file.jpg\\*.*'


This happens, because the result of the stat call states that the path is a directory, although it is a regular jpg file. If I start an interactive python or nodejs shell and call stat for the reported file, the return value looks ok this time (correct type, size etc.). It looks like the samba client on Windows 10 bungles whentoo many stat calls are issued in a short time interval.

Is this a known problem? To me it looks like a fatal bug. Is there a way to get around is problem by using some Windows 10 settings?

In my case the script is actually the base for a backup application ... which will totally do the wrong thing if file sizes and types are returned incorrectly.

Note: I tested 2 Windows clients running Windows 10. The 3 tested samba servers are running Ubuntu using pretty much Ubuntu's default smbd configs (besides share definitions). I also tried to force SMB2 but that didn't change anything.

Appendix:

The python script. The nodejs script (not listed here) does pretty much the same thing:

from os import listdir, stat
from os.path import join
from stat import *

files = []
todo = ['y:\\'] # y:\\ is a mounted samba share

while len(todo) > 0:
    next = todo.pop(0)
    childs = listdir(next)
    for child in childs:
        childPath = join(next, child)
        childStat = stat(childPath)
        mode = childStat.st_mode
        if S_ISREG(mode):
            files.append(childStat)
        elif S_ISDIR(mode):
            todo.append(childPath)

print len(files) # Will not be called because error is thrown before on Windows 10



Active Directory - Disabled Account/Users

$
0
0

Hi,

Good day.

Please HELP! I have lists of ID (UserIDs) that is already disabled and I want to remove their member groups for every listed disabled user in AD. Is this possible?

Thanks a lot in advance.

Start-WBHyperVRecovery : The specified backup storage location is invalid.

$
0
0

Hi everyone,

I made a backup of a VM on one Hyper-V host. Now I try to restore it on another using Powershell:

$VMName = 'myVM'
$volumeName = 'myVM_bak'
$MachineName = 'host1'
$TargetPath = 'E:\HV'

$WBVolume = Get-WBVolume -AllVolumes | ? {$_.VolumeLabel -eq $volumeName}
$WBBackupTarget = New-WBBackupTarget -Volume $WBVolume
$WBBackupSet = Get-WBBackupSet -BackupTarget $WBBackupTarget -MachineName $MachineName | Select-Object -Last 1
$WBVirtualMachines = ($WBBackupSet.Application | ? Identifier -eq 'HyperV').Component | ? VMName -eq $VMName 
Start-WBHyperVRecovery -BackupSet $WBBackupSet -VMInBackup $WBVirtualMachines -Force -UseAlternateLocation -TargetPath $TargetPath -RecreatePath
I get an error "Start-WBHyperVRecovery: specified backup storage location is invalid."

I can restore the VM using Windows Server Backup UI without any problem. But I need to restore the VM every day.

The both Hyper-V servers are Windows Server 2012 R2

The same question in the "Backup – Windows and Windows Server" forum

remote invoke a bat

$
0
0

Support I have server A and Server B. there is a script in Server B C:\temp\script\test.bat

how to invoke C:\temp\script\test.bat in Server B from Server A using powershell in ServerA ?

Is it possible to run a script on another computer that are having the same network drive?

$
0
0

HI,

I have PC A en PC B which have both a common network-drive. Is it possible to execute a script on PCA that runs the script on PC B? I know its a strange question. But perhaps its possible? I am not authorized for Powershell Remote scripting.

Gr. P


Parameters and variables with colon :

$
0
0

Hello Guys, 

yesterday, i tried install DC via power-shell and I notice, that some parameters are like -InstallDns:$true,-CreateDnsDelegation:$false,-Force:$true. 

Why are this variables with : ? I haven't met with this type... Usually is -something $true, -something $false etc ..... without : colon.

Task Scheduler Hidden powershell with no popup

$
0
0

Does anyone knows how to make the Task Scheduler to start to run ps1 script as Hidden without Poping up the window for a second (so to say - background task)...

Currently I am using as arguments:

-nologo -windowstyle Hidden -file FileLocation

But even if the script runs in background - it still at the beginnings pops up for a second - before hides it-self...

I just want to log into the log file the result of: netstat -f -b

EDIT:

I found a solution (maybe though not the best one): I set up to run that script as SYSTEM - but to make it more secured in this case - I set the script to be editable only by Administrator... Even System can't edit it without Admin rights...


Need help getting back to CMD shell after executing PS command.

$
0
0

I have a batch file that we use to complete some pushes here at work. It's pretty lengthy and I am sure this would be better suited from another scripting language but at the moment my knowledge is limited so I am forced to work with what I know.  

I've taken the basics out of my script and broke it down for ease in hopes that someone can assist. 

Basically I have a script that prompts you to input what option you want, then based on that user input it will execute a task within the script. Next we have a series of steps that needed to be run synchronously and also needed to be displayed in its own window for monitoring purposes as well as written to a log file. This series of steps is handled by using PS. My issue is the script needs to continue back in the command shell and this is where I am stuck. After the PS runs the commands the original CMD shell is stuck waiting... I need this to continue with the batch script: 

@ECHO OFF
echo:
:start
SET /P _inputname= Please select what env you are pushing to (env1, env2, env3 ):
IF "%_inputname%"=="env1" GOTO :env1
IF "%_inputname%"=="env2" GOTO :env2
IF "%_inputname%"=="env3" GOTO :env3
ECHO INVALID PUSH ID
GOTO :start
:env1
ECHO This is a env1 test script
ping -t 3.139.240.1>logs\pinggateway.txt | start "ping gateway" powershell Get-Content logs\pinggateway.txt -Wait -Tail 10 | ping apple.com>logs\Appleresults.txt | start "process 2" powershell Get-Content logs\Appleresults.txt -Wait -Tail 10 | ping -t 3.139.240.100>logs\randomIP.txt | start "Random IP" powershell Get-Content logs\RandomIp.txt -Wait -Tail 10

:env1pt2
set /p var=This is where I need to continue with my script and it never gets to this point [OK]:
if %var%== OK goto :env1nextstep
if %var%== exit/end/quit/q goto :END

:env1nextstep
.....blah blah blah
GOTO :end

:env2
ECHO Starting up env2 test script
GOTO :end

:env3
ECHO Starting up env3 test script
:end 

When I select "env1" I will get three PS windows opened with results of the commands, logs created for each window but my original CMD window looks like this:

Please select what env you are pushing to (env1, env2, env3 ):env1
This is a env1 test script



Viewing all 21975 articles
Browse latest View live


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