PowerShell script to check if directory is shared or not? - shell

I am using the following command in PowerShell 2.0 to check if the particular folder is shared or not but I am getting an error.
[bool](Get-WmiObject -Class Win32_Share -ComputerName ravenPC -Filter "Path='D:\websites\website1'")
Also, I want to store the value of bool in a variable and check it each time if it's true or false. Can someone help me on this.
The error I get is as follows:
Get-WmiObject : Invalid query
At line:1 char:21
+ [bool](Get-WmiObject <<<< -Class Win32_Share -ComputerName ravenPC -Filter "Path='D:\websites\website1'")
+ CategoryInfo : InvalidOperation: (:) [Get-WmiObject], ManagementException
+ FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

You need to escape the backslashes in your WMI query:
[bool](Get-WmiObject -Class Win32_Share -ComputerName ravenPC -Filter "Path='D:\\websites\\website1'")

Related

Powershell Restart Script

I'm attempting to write a script that gives me a running list of computers whose name starts with SOU-C128*. I'm assigning the list to a variable and using it as input for the restart-computer cmdlet. However, I'm recieving the error provided:
restart-computer : Computer name #{Name=SOU-C127-04} cannot be resolved with the exception: One or more errors occurred..
At \\nas\user\IT\restart.ps1:2 char:1
+ restart-computer -computername $computers -force -wsmanauthentication ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (#{Name=SOU-C127-04}:String) [Restart-Computer], InvalidOperationException
+ FullyQualifiedErrorId : AddressResolutionException,Microsoft.PowerShell.Commands.RestartComputerCommand
This is the script
$computers=Get-ADComputer -Filter * | Where-Object {$_.Name -like "sou-c127*"} | Select -Property Name | Sort Name
restart-computer -computername $computers -force -wsmanauthentication Kerberos
Please assist!
Thanks.
Your immediate fix would be to use $computers.name or, expand the property in your Get-ADComputer by using Select-Objet -ExpandProperty 'Name'; foreach name would suffice too.
Wanted to suggest something though. In PowerShell when you're filtering, you always want to filter as far left as possible. This can become computationally expensive running a pipeline filter such as Where-Object on a large list. In your case: Get-ADComputer -Filter *, you're filtering for every computer, then filtering again. You can cut that out by filtering using the filter in your Get-ADComputer cmdlet to begin with:
$computers = Get-ADComputer -Filter "Name -like 'sou-c127*'" | Sort-Object -Property 'Name'
Restart-Computer -ComputerName $computers.Name

Why is invoke-command and new-pssession not working?

I have no idea why this isn't working. Any ideas? I honestly don't know what else I can try.
I plan to add it to a script that prompts the user for a computername / domain creds but I can't get it to work in a shell window for starters.
Here's the line:
Invoke-Command -Session New-PSSession -ComputerName server001 -ScriptBlock {shutdown.exe /r -t 0}
Here's the error:
Invoke-Command : Cannot bind parameter 'Session'. Cannot convert the "New-PSSession" value of type "System.String" to
type "System.Management.Automation.Runspaces.PSSession".
At line:1 char:25
+ Invoke-Command -Session New-PSSession -ComputerName server001 -Scrip ...
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-Command], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.InvokeCommandCommand
Sorry for not having anything further to add to this but I'm still trying to learn PowerShell and need guidance.
As the error indicates, the -Session parameter accepts arguments of type PSSession - and to create such an object we need to invoke New-PSSession (not just pass it's name as an argument):
$session = New-PSSession -ComputerName computer01
Invoke-Command -Session $session { ... }
If you don't plan on reusing the session later, you can simply pass the computer name directly to Invoke-Command, it'll handle session management for you implicitly:
Invoke-Command -ComputerName computer01 { ... }

Copy-Item for copy files from local to remove server using credentials

I am trying to copy some files and folder from my local machine to a remote server:
Copy-Item .\copy_test.txt -destination "\\serverip\c$\backups\"
but I'm getting an error:
Copy-Item : Logon failure: unknown user name or bad password.
At line:1 char:10
+ Copy-Item <<<< .\copy_test.txt -destination "\\serverip\c$\backups\" -verbose
+ CategoryInfo : NotSpecified: (:) [Copy-Item], IOException
+ FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.CopyItemCommand
I was trying using credentials but this command does not allow -Credential argument. I was searching a lot and in every example the command is pretty easy just executing the Copy-Item $source -destination $destination and I wonder why is so hard in my workstation.
Creating New PSDrive
I tried to create a New-PSDrive but it didn't work.
$creds = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $username, $password
New-PSDrive -Name X -PSProvider FileSystem -Root '\\$serverip\c$' -Credential $creds -Persist
Copy-Item '.\copy_test.txt' -Destination 'X:\backups'
Remove-PSDrive -Name X
It is the error message:
PS C:\Users\Administrator\Desktop> .\copyfiles.ps1
New-PSDrive : The network path was not found
At C:\Users\Administrator\Desktop\copyfiles.ps1:11 char:1
+ New-PSDrive -Name X -PSProvider FileSystem -Root '\\$serverip\c$' -Credential $c ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (X:PSDriveInfo) [New-PSDrive], Win32Exception
+ FullyQualifiedErrorId : CouldNotMapNetworkDrive,Microsoft.PowerShell.Commands.NewPSDriveC
Copy-Item : Cannot find drive. A drive with the name 'X' does not exist.
At C:\Users\Administrator\Desktop\copyfiles.ps1:12 char:1
+ Copy-Item '.\copy_test.txt' -Destination 'X:\backups'
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (X:String) [Copy-Item], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.CopyItemCommand
Remove-PSDrive : Cannot find drive. A drive with the name 'X' does not exist.
At C:\Users\Administrator\Desktop\copyfiles.ps1:13 char:1
+ Remove-PSDrive -Name X
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (X:String) [Remove-PSDrive], DriveNotFoundExcepti
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.RemovePSDriveCommand
My servers
My server are windows instances in AWS. I have the right permission because I am able to run other command like Invoke-Command in order to inspect some services into the remote server.
PS> $PSVersionTable.PSVersion
Major Minor Build Revision
----- ----- ----- --------
4 0 -1 -1
If credentials are required for access to a remote share you need to map it to a (PS)drive before you can use it with other cmdlets.
$cred = Get-Credential
New-PSDrive -Name X -PSProvider FileSystem -Root "\\$serverip\c$" -Credential $cred -Persist
Copy-Item '.\copy_test.txt' -Destination 'X:\backups'
Remove-PSDrive -Name X
I found the solution. I was using PowerShell version 4.0 and then upgrade my version to 5.0
In previous version the Copy-Item doesn't allow credentials. Now is possible to copy files through the sessions between servers:
$deploy_dest = "C:\backup"
$username = "$server\Administrator"
$password = Get-Content C:\mypassword.txt | ConvertTo-SecureString -AsPlainText -Force
$creds = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
$session = New-PSSession -ComputerName $server -Credential $creds
Copy-Item -Path .\copy_test.txt -Destination -ToSession $session
Check this alternative using copy command and net use
net use \\10.164.60.77\c$\Users\ana\Desktop password /user:username
copy "C:\Users\alex\Desktop\test.txt" "\\10.164.60.77\c$\Users\ana\Desktop\test.txt"

Powershell's Invoke-Command won't take in a variable for -ComputerName parameter

I just can't seem to get this to work, and I can't figure out how to google this issue. similar script is working remotly but now i need to made it work localy. But... Please check the script...
Function Local-Install {
$ComputerName = "$env:computername"
$AppName = "Deployment"
Invoke-Command -ComputerName $ComputerName ,$AppName -ScriptBlock `
{
param ($ComputerName,$AppName)
write-host "Getting Parameters for '$AppName' on $ComputerName"}
$Application = Get-WmiObject -computername $ComputerName -Namespace "root\ccm\ClientSDK" -Class CCM_Application | where {$_.Name -like "$AppName"} | Select-Object Id, Revision, IsMachineTarget
$AppID = $Application.Id
$AppRev = $Application.Revision
$AppTarget = $Application.IsMachineTarget
([wmiclass]'ROOT\ccm\ClientSdk:CCM_Application').Install($AppID, $AppRev, $AppTarget, 0, 'Normal', $False)
}
and i get an error like this:
Invoke-Command : One or more computer names are not valid. If you are trying to pass a URI, use the -ConnectionUri parameter, or pass URI objects ins
tead of strings.
At line:5 char:1
+ Invoke-Command -ComputerName $ComputerName ,$AppName -ScriptBlock `
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (System.String[]:String[]) [Invoke-Command], ArgumentException
+ FullyQualifiedErrorId : PSSessionInvalidComputerName,Microsoft.PowerShell.Commands.InvokeCommandCommand
Exception calling "Install" : ""
At line:13 char:1
+ ([wmiclass]'ROOT\ccm\ClientSdk:CCM_Application').Install($AppID, $AppRev, $AppTa ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WMIMethodException
Since this is local you could just run the "env:COMPUTERNAME" call in the method. However, if you want to get this to work as is, you just need to add the -ArgumentList argument to the Invoke-Command call:
Invoke-Command -ComputerName $ComputerName, $AppName -ArgumentList $ComputerName, $AppName -ScriptBlock `

Using PSCredential Object to authenticate commands non-interactively

I am using the PSCredential Object to authenticate a command, which I need to be run as a different user.
I get the following on the powershell cli.
> whoami
dmn1\srveikafka
> $secpasswd = ConvertTo-SecureString "mypassword" -AsPlainText -Force
> $mycreds = New-Object System.Management.Automation.PSCredential ("srveizookeeper", $secpasswd)
>
> $sess = new-pssession -computername remotecomputer.xyz.com -credential $mycreds
> invoke-command -session $sess -scriptblock {whoami}
dmn1\srveizookeeper
But when I run these same commands as a powershell script I get this error.
new-pssession : [remotecomputer.xyz.com] Connecting to remote server remotecomputer.xyz.com failed with the following
error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic.
At C:\workstation\add_zookeeper_spn.ps1:13 char:9
+ $sess = new-pssession -computername remotecomputer.xyz.com -credential $mycreds
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotin
gTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed
Invoke-Command : Cannot validate argument on parameter 'Session'. The argument is null or empty. Provide an argument
that is not null or empty, and then try the command again.
At C:\workstation\add_zookeeper_spn.ps1:14 char:25
+ invoke-command -session $sess -scriptblock {whoami}
+ ~~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-Command], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
What am I getting wrong or missing?
You might need to include the domain as part of the username in the credential constructor:
$mycreds = New-Object System.Management.Automation.PSCredential ("dmn1\srveizookeeper", $secpasswd)

Resources